如何将状态传递给 React.js 中的动作? [英] How can I pass state to an action in React.js?

查看:35
本文介绍了如何将状态传递给 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

这篇关于如何将状态传递给 React.js 中的动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆