繁体   English   中英

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

[英]How can I get the updated state with 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

First dispatch 将值更改为 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 存储传递到您的组件作为道具。 Component1方法被执行并且可能会改变 Redux 状态(就像它在你的示例中所做的那样)。 但是更新的道具不会立即可用。 props只是参数,已由connect函数传递。 要更改任何函数的参数,您应该再次调用它。 因此,在收到更新的petsconnect将再次使用更新的pets调用您的组件。 但它会在以后。

connect() - >调用Component1并传递props.pets = false - > Compoentn1设置pets在终极版到true - > connect()接收更新的pets并调用Component1props.pets = true

这就是setTimeout的技巧起作用的原因。 Ste 超时只是等待Component1第二次调用

为了解决您的确切问题,如果您知道您已经更新了它,请不要从props读取pets

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

暂无
暂无

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

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