javascript - 如何将状态传递给 React.js 中的操作?

标签 javascript reactjs redux

我的组件中有一些状态我想传递给一个 Action 在 React.js 中。我怎样才能做到这一点?

mycomponent.js

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

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
        }
    })
    }
}

它不工作。我的代码有问题吗? 当我在操作中记录该城市变量时,它只是未定义

最佳答案

setState 不会立即更新 this.state。这是 React docs 的解释:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

这意味着您需要存储传递给 setState 的值,并将其传递给您的操作创建者。像这样的东西(我没有运行这个代码,确保你测试它)应该工作:

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

关于javascript - 如何将状态传递给 React.js 中的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335936/

相关文章:

Javascript/Jquery 搜索字符串中是否存在单词

javascript - 如何创建适合移动设备的响应式菜单?

javascript - 我正在尝试使用 process.env 和 smtp gmail 在 meteor 中发送电子邮件

javascript - babel obj symbol.iterator 未定义

javascript - 检测数字输入的箭头已被单击 React

javascript - 如何获得 react 返回元素的长度?

reactjs - 使用 react 动态加载图片

javascript - React Redux 表单 2 使用 onSubmit 和重定向提交

javascript - 如何映射每个对象值都有唯一 id 的对象并将这些值返回到 React 组件

javascript - React-native:在从存储中获取数据之前渲染 View