简体   繁体   English

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

[英]How can I pass state to an action in React.js?

I have some state in my component that I want to pass to an action in React.js. 我的组件中有一些状态要传递给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
        }
    })
    }
}

It's not working. 没用 Is there something wrong in my code? 我的代码有问题吗? When I log that city variable in my action it's just undefined . 当我在操作中记录该城市变量时,它只是undefined

setState won't immediately update this.state . setState不会立即更新this.state Here is the explanation from the React docs : 这是React docs的解释:

setState() does not immediately mutate this.state but creates a pending state transition. setState()不会立即使this.state突变,但会创建一个挂起的状态转换。 Accessing this.state after calling this method can potentially return the existing value. 调用此方法后访问this.state可能会返回现有值。

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. 无法保证对setState的调用的同步操作,并且可能会为提高性能而批量调用。

That means you'd need to store the value you are passing to setState , and pass that to your action creator as well. 这意味着您需要存储要传递给setState的值,并将其也传递给动作创建者。 Something like this (I didn't run this code, make sure you test it) should work: 这样的事情(我没有运行此代码,请确保您对其进行了测试)应该可以工作:

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

You should be using the setState callback ie 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. 您应该使用setState回调,即处理状态突变的正确方法,因为setState需要花费时间才能使状态发生变化,因此,在更新状态后立即使用状态可能会导致产生较旧的值,而不是更新后的值。

Make use of callback like 像这样利用回调

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

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 确保您在constructor函数中或从调用它的位置绑定了cityHandleUpdateInput函数,否则它本身将无法使用this.setState访问setState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM