我开始在一个新项目中实现还原器模式,我想知道useReducer钩子是否与async immutability与useState钩子有相同的问题。
我的意思是:
const [state, setState] = useState('');
const handleChange = e => {
setState(e.target.value);
// It doesn't give the current value, it gives the previous one, which is ''
console.log(state);
// So i need to set the current value in a variable to avoid the async immutability
const currentValue = e.target.value;
console.log(currentValue);
e.stopPropagation();
}
<input type='text' value={state} onChange={handleChange}>PRESS</button>对于change钩子,我需要做同样的事情:在 variable中设置当前的?
发布于 2020-03-16 11:21:14
问题求解
为了避免useReducer挂钩不可变,我们需要在variable中设置current value。然后访问那个变量。
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>https://stackoverflow.com/questions/60704906
复制相似问题