[英]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
函數傳遞。 要更改任何函數的參數,您應該再次調用它。 因此,在收到更新的pets
, connect
將再次使用更新的pets
調用您的組件。 但它會在以后。
connect()
- >調用Component1
並傳遞props.pets = false
- > Compoentn1
設置pets
在終極版到true
- > connect()
接收更新的pets
並調用Component1
與props.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.