我做错了什么 Hooks 相关
What am I doing wrong Hooks Related
我是 hooks 的新手,所以我会问这个问题:
如何在 onChange 函数中合法使用 setState ??
{
const state = useState([{date: date}]);
};
这会引发错误:(
预期:更新状态
结果报错:Hooks can only be called inside of a function component.
我确实在网上找到了一些关于安装多个 React 版本的答案,但这里不是这样:)
您需要在主组件函数体中声明您的钩子:
const MyComponent = () => {
// declaring your useState Hook - it returns a getter and setter
const [date, setDate] = useState(null)
const myCallback = (newDate)=>{
// you can read the state
const state = date;
// or, you can do the equivalent of setState
setDate(newDate)
}
return // return your .jsx
}
需要注意的是你声明你的钩子一次,它returns两个参数,一个getter和一个setter.从那时起,您只能使用 getter 和 setter 与那个原始 Hook 交互。
对于您的 pastebin 代码:
const [myState,setMyState] = useState(
{
name: "",
type: props.navigation.getParam("serviceName"),
date: "15-05-2018",
imageURI: props.navigation.getParam("imageURI")
});
const handleChange = e => {
setMyState(prevState=> {...prevState, name: e.nativeEvent.text})
};
(我用过 myState
和 setMyState
但它们可以是你喜欢的任何东西)
嗯,看来你搞错了……
当我们像 class,
那样使用钩子时,没有单一状态
const [item, setValue] = useState(null)
这会将状态变量 "item" 设置为初始值 null。现在我们可以使用 "setValue" 将 "item" 的值更改为我们想要的值
setValue(5)。没有像 class 组件那样的 setState。由于状态变量的值已更改,因此组件重新呈现。我们可以声明多个 state-variables 比如
const [newitem, setnewItemValue] = useState(null)
每当 state-variable 更改时,组件将重新呈现
我是 hooks 的新手,所以我会问这个问题:
如何在 onChange 函数中合法使用 setState ??
{
const state = useState([{date: date}]);
};
这会引发错误:(
预期:更新状态 结果报错:Hooks can only be called inside of a function component.
我确实在网上找到了一些关于安装多个 React 版本的答案,但这里不是这样:)
您需要在主组件函数体中声明您的钩子:
const MyComponent = () => {
// declaring your useState Hook - it returns a getter and setter
const [date, setDate] = useState(null)
const myCallback = (newDate)=>{
// you can read the state
const state = date;
// or, you can do the equivalent of setState
setDate(newDate)
}
return // return your .jsx
}
需要注意的是你声明你的钩子一次,它returns两个参数,一个getter和一个setter.从那时起,您只能使用 getter 和 setter 与那个原始 Hook 交互。
对于您的 pastebin 代码:
const [myState,setMyState] = useState(
{
name: "",
type: props.navigation.getParam("serviceName"),
date: "15-05-2018",
imageURI: props.navigation.getParam("imageURI")
});
const handleChange = e => {
setMyState(prevState=> {...prevState, name: e.nativeEvent.text})
};
(我用过 myState
和 setMyState
但它们可以是你喜欢的任何东西)
嗯,看来你搞错了……
当我们像 class,
那样使用钩子时,没有单一状态const [item, setValue] = useState(null)
这会将状态变量 "item" 设置为初始值 null。现在我们可以使用 "setValue" 将 "item" 的值更改为我们想要的值 setValue(5)。没有像 class 组件那样的 setState。由于状态变量的值已更改,因此组件重新呈现。我们可以声明多个 state-variables 比如
const [newitem, setnewItemValue] = useState(null)
每当 state-variable 更改时,组件将重新呈现