[英]React Class to Function components
I'm on the step of converting one of my Class components to a functional one, however, I'm thinking of better way of handling state from the functional version.我正在将我的 Class 组件之一转换为功能组件,但是,我正在考虑从功能版本处理 state 的更好方法。
Currently, here is my Class component state:目前,这是我的 Class 组件 state:
this.state = {
email: "",
password: "",
errors: {},
};
On functional component version,Currently I would have to break those states into three different states using UseState:在功能组件版本上,目前我必须使用 UseState 将这些状态分成三种不同的状态:
const [email, setEmail] = useState("");
const [password, setpassword] = useState("");
const [errors, setErrors] = useState({});
is there a way to combine these states in 1 state that is an object by default like this:有没有办法将这些状态组合在 1 state 中,默认情况下是 object,如下所示:
const [states,setStates] = useState({
email:"",
password:"",
errors:{}
});
Reason why is because I have this kind of code from my class components, and I dont think this will work if I opted for the first Functional comp.原因是因为我的 class 组件中有这种代码,如果我选择第一个函数式组件,我认为这不会起作用。 setup:
设置:
handleChange = (event) => {
this.setState({
[event.target.name]: event.target.value,
});
};
Yes you can do that.是的,你可以这样做。 But you have to modify your setState Function like this
但是你必须像这样修改你的setState Function
handleChange = (event) => {
setStates({ ...states , [event.target.name]: event.target.value})
};
you have to do this on every setState call wherever you do.无论您身在何处,都必须在每次 setState 调用时执行此操作。
Yes you can achieve that using a custom hook:是的,您可以使用自定义挂钩来实现:
const useLegacyState = initialState => {
return useReducer((prevState, newState) => {
return typeof newState === 'function'
? { ...prevState, ...newState(prevState) }
: { ...prevState, ...newState };
}, initialState);
};
And usage:和用法:
const [states, setStates] = useLegacyState({
email: '',
password: '',
errors: {}
});
const handleChange = event => {
setStates({
[event.target.name]: event.target.value
});
};
Yes, the structure of the state variable is totally up to you.是的,state 变量的结构完全由您决定。
Note, however, that this means that every time you call setStates
you'll need to provide the entire structure.但是请注意,这意味着每次调用
setStates
时都需要提供整个结构。
You can use something like Object.assign
to "update" existing state like this:您可以使用类似
Object.assign
的东西来“更新”现有的 state,如下所示:
setStates(Object.assign({}, states, {a: 'b'}));
This would add the a
key with a b
value to the state, without changing previous ones.这会将具有
b
值的a
键添加到 state,而不更改之前的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.