我有一个用于状态管理的 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
-> Compoentn1
套pets
在 Redux 中为 true
-> connect()
收到更新pets
并调用Component1
与 props.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/