Javascript React-useReducer和useState
我开始在一个新项目中实现减速器模式,我想知道Javascript React-useReducer和useState,javascript,reactjs,state,react-hooks,Javascript,Reactjs,State,React Hooks,我开始在一个新项目中实现减速器模式,我想知道 useReducerhook与useStatehook在async不变性方面存在相同的问题 我的意思是: const[state,setState]=useState(“”); 常量handleChange=e=>{ 设置状态(如目标值); //它没有给出当前值,而是给出上一个值,即“” console.log(状态); //所以我需要在变量中设置当前值以避免异步不变性 const currentValue=e.target.value; conso
useReducer
hook与useState
hook在async不变性方面存在相同的问题
我的意思是:
const[state,setState]=useState(“”);
常量handleChange=e=>{
设置状态(如目标值);
//它没有给出当前值,而是给出上一个值,即“”
console.log(状态);
//所以我需要在变量中设置当前值以避免异步不变性
const currentValue=e.target.value;
console.log(当前值);
e、 停止传播();
}
按
对于useReducer
钩子,我需要做同样的事情:在变量中设置当前change
?无论使用什么useState
或useReducer
,您都会在下一个渲染周期中看到更新的值
这不是一个缺陷,而是一个设计。如果要使用更新的值执行某些操作,请使用useffect
,它将在每次渲染后运行
因此,它将具有新的价值。问题已解决
为了避免useReducer
钩子不变性,我们需要在变量中设置当前值。然后访问该变量
const initialState = {
value: ''
};
const [state, dispatch] = useReducer(SomeReducerFunction, initialState);
const handleChange = e => {
dispatch({type: SOME_ACTION_TYPE, payload: e.target.value });
const currentValue = e.target.value;
console.log(currentValue);
e.stopPropagation();
}
<input type='text' value={state} onChange={handleChange}>PRESS</button>
const initialState={
值:“”
};
const[state,dispatch]=useReducer(SomeReducerFunction,initialState);
常量handleChange=e=>{
分派({type:SOME\u ACTION\u type,payload:e.target.value});
const currentValue=e.target.value;
console.log(当前值);
e、 停止传播();
}
按
按?不设置受控部件。但要访问当前值,必须执行相同的操作。我可以知道您的用例吗?从输入中获取值
,并在一些段落中设置它以显示它的信息
const initialState = {
value: ''
};
const [state, dispatch] = useReducer(SomeReducerFunction, initialState);
const handleChange = e => {
dispatch({type: SOME_ACTION_TYPE, payload: e.target.value });
const currentValue = e.target.value;
console.log(currentValue);
e.stopPropagation();
}
<input type='text' value={state} onChange={handleChange}>PRESS</button>