React Hooks中 useState修改状态

使用hooks函数,所有的hooks函数包括自己定义的hooks函数都应该以 useState开头 

react hooks函数错误提示插件 eslint-plugin-react-hooks,安装好插件后在pack.json中进行配置错误提醒

 "eslintConfig": {
    "extends": "react-app",
    "plugins": ["react-hooks"],
    "rules": {
      "react-hooks/rules-of-hooks": "err"
    }
  },

 

useState可以传入使用默认值,也可以传入一个函数延迟初始化

// hooks组件,直接设置默认值
function App() {
  const [count, setCount] = useState(0) // useState 默认值 0 返回一个数组,第一个是变量,第二个修改变量的方法
  return (
    
); }
// 函数返回默认值
function App(props) {
  const [count, setCount] = useState(() => {
    return props.defaultValue || 0
  }); // useState 函数返回默认值
  return (
    
); }

 

你可能感兴趣的:(react)