反应-useReducer和useState

时间:2020-03-16 11:12:52

标签: javascript reactjs state react-hooks

我开始在新项目中实现reducer模式,我想知道是否 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>

对于useReducer钩子,我需要做同样的事情:change中设置当前的variable 吗?

2 个答案:

答案 0 :(得分:0)

无论使用什么useStateuseReducer,您都会在下一渲染周期中看到更新的值。

这不是缺陷,而是设计。如果您想对更新后的值进行处理,请使用useEffect,它会在每次渲染后运行。

因此它将具有新鲜的价值。

答案 1 :(得分:0)

已解决的问题

为避免useReducer挂钩不变性,我们需要在current value中设置variable。然后访问该变量。

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>