javascript - 如何使用 redux 获取更新后的状态

标签 javascript reactjs asynchronous redux react-redux

我有一个用于状态管理的 React 项目和 redux。这些是我的行动。

const mapDispatchToProps = dispatch => ({
  handleChange: (name, value) => { dispatch(handleChange(name, value)) },
  filterRooms: (rooms) => { dispatch(filterRooms(rooms)) }
});

我必须一一使用这两种方法。

this.props.handleChange(pets, true);  // handle changes
this.filterRooms();   // filtering with changing value

filterRooms = () => {
  let {rooms,pets} = this.props; // Here I should get pets === true but it's false.

  // filter by pets
  if (pets) {
    tempRooms = tempRooms.filter(room => room.pets === true);
  }

  this.props.filterRooms(tempRooms);
}

如果我使用 setTimeout 作为第二种方法,那没问题,但我认为这不是正确的方法。

this.props.handleChange(name, value);
setTimeout(() => {
   this.filterRooms();
}, 500);

最佳答案

似乎下面两个函数依次运行,一个接一个

this.props.handleChange(pets, true);  // handle changes
this.filterRooms();   // filtering with changing value

首先将更改后的值发送到 Redux。并且它在那里更新(如 setTimeout 的示例)。但不要指望 Redux 的更新值会立即提供给 this.filterRooms() .

你有一些 Reactjs 组件。 Reactjs 组件本质上是类或函数。然后你将其换入connect 。所以你的代码可能看起来像这样

class Component1 extends React.Component {
    onChange: () => {
        this.props.handleChange(pets, true);  // handle changes
        this.filterRooms();   // filtering with changing value
    }
    // other staff
}

export default connect(mapStateToProps, mapDispatchToProps)(Component1)

React 中发生了什么。它实例化类 Component1 ,然后调用connect它反过来调用你的类的一些方法(即 render() 或其他)。 connect还将 Redux 存储中的一些值作为 props 传递给您的组件。方法Component1被执行并且可能会更改 Redux 状态(就像在您的示例中所做的那样)。但更新后的 Prop 不会立即可用。 props只是参数,已通过 connect 传递功能。要更改任何函数的参数,您应该再次调用它。所以收到更新后pets , connect将再次调用您的组件并更新 pets 。不过那是以后的事情了。

connect() -> 来电Component1并通过props.pets = false -> Compoentn1pets在 Redux 中为 true -> connect()收到更新pets并调用Component1props.pets = true

这就是为什么用 setTimeout 来欺骗的原因作品。 Ste超时只是等待Component1的第二次调用

要解决您的具体问题,请勿阅读 pets来自props如果您知道您已经更新了它。

this.props.handleChange(pets, true);  // handle changes
this.filterRooms(true);   // filtering with changing value

filterRooms = (pets) => {
  let {rooms} = this.props; 

  // filter by pets
  if (pets) {
    tempRooms = tempRooms.filter(room => room.pets === true);
  }

  this.props.filterRooms(tempRooms);
}

关于javascript - 如何使用 redux 获取更新后的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294001/

相关文章:

javascript - 如何在 Vue setup() 方法中访问 Vuex 商店?

javascript - 使用导航栏滚动 - 未捕获的类型错误 : Cannot read property 'top' of undefined

reactjs - 命名空间 'React' 没有导出成员 'FC'

javascript - 在不改变原始数组的情况下过滤 javascript 树

javascript - 异步,回调,关闭,哦,我的

javascript - Nodejs 一次触发两个请求

JavaScript - 输入提交按钮 (html) 以激活 JavaScript 功能不工作

reactjs - 如何使用 Material-UI ThemeProvider 和 createGenerateClassName 避免类名冲突

c++ - 为什么从 `std::async` 阻塞返回的 future 的析构函数?

javascript - 如何阻止事件循环直到完成运行异步任务