如何从useEffect中的usereducer挂钩获取状态?

时间:2019-05-13 18:19:43

标签: javascript reactjs react-hooks

我将方法绑定到useEffect挂钩内的按钮,并且该方法在内部使用状态。但是我没有将要绑定的方法中的更新状态,而是将状态值作为initialSate

如果我将代码拉到useEffect钩子之外,则一切正常,但不确定这是否正确。

function Test() {
    const initialState = { name: ''}
    const reducer = () => {...}
    const [state, dispatch] = useReducer(reducer, initialState);
    const save = (): void => {
        ...
         const { name } = state;
         // here i am getting state value as the initialState and not the
         // updated state value
        ...
    }
    useEffect(() => {
        ...
        bindActionToButton(button, save);
        ...
    }, []);
}

save方法绑定到按钮的click事件上。单击按钮时,状态内部的状态值应该是更新后的状态值,但我将值作为initalState值获取。如果我调用将代码拉到useEffect之外,则一切正常。

0 个答案:

没有答案
相关问题