我的组件中有一些状态我想传递给一个 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 mutatethis.state
but creates a pending state transition. Accessingthis.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/