如何将状态传递给 React.js 中的动作?

如何将状态传递给 React.js 中的动作?

问题描述:

我的组件中有一些状态要传递给操作在 React.js 中.我该怎么做?

I have some state in my component that I want to pass to an action in React.js. How can I do this?

mycomponent.js

mycomponent.js

cityHandleUpdateInput() {
    this.setState({
        city: this.refs.city.refs.searchTextField.input.value
    })
    const { city } = this.state;
    this.props.fetchResCity(city)
}

myaction.js

myaction.js

export const fetchResCity = (city) => (dispatch, getState) =>  {
if (!getState().resCity.isFetching) {
    console.log(getState().city)
    console.log(city)
    const endpoint = 'rescity?city=${city}';
    dispatch({
        [CALL_API]: {
            types: [ RES_CITY_REQUEST, RES_CITY_SUCCESS, RES_CITY_FAILURE ],
            endpoint: endpoint
        }
    })
    }
}

它不起作用.我的代码有问题吗?当我在操作中记录该城市变量时,它只是 undefined.

It's not working. Is there something wrong in my code? When I log that city variable in my action it's just undefined.

您应该使用 setState 回调,即处理状态变化的正确方法,因为 setState 需要时间改变状态,因此在更新状态后立即使用状态可能会导致旧值而不是更新值.

You should be using the setState callback i.e a correct way to handle state mutations since setState takes time to mutate the state and hence any use of state immediately after updating the state may result in the older value and not the updated value.

利用回调之类的

cityHandleUpdateInput() {
    this.setState({
        city: this.refs.city.refs.searchTextField.input.value
    }, () => {
        const { city } = this.state;
        this.props.fetchResCity(city)
    })  
}

确保您在 constructor 或从它被调用的地方绑定了 cityHandleUpdateInput 函数,否则它本身将无法访问 setStatethis.setState

Make sure that you are binding the cityHandleUpdateInput function in constructor or from where it is being called or otherwise it itself won't be able to access the setState with this.setState