我的应用程序中有两个容器组件。我刚开始使用 react、redux 并认为容器组件从其各自的 reducer 获取状态对象,以便它可以映射到组件的 props。
我在控制台记录了 reducer 发送的状态,并看到状态对象也包含我应用程序中另一个 reducer 发送的数据。我认为它应该只从其对应的 reducer 获取数据,因为 reducer 将数据发送到容器组件。
我不知道是我做错了什么还是事情就是这样。
reducer :
export default function(state=null, action){
console.log(action);
switch(action.type){
case 'BOOK_SELECTED':
return action.payload
}
return state;
}
容器组件:
function mapStateToProps(state){
console.log("state from reducer",state); //contains data from the other reducer as well
return {
bookDetail : state.bookDetail
}
}
export default connect(mapStateToProps)(BookDetail);
最佳答案
容器和 reducer 不是“连接的”。这就是 mapStateToProps
存在的原因。
Redux 不知道容器需要状态的哪些部分,因此,在 mapStateToProps
中,提供了所有状态,每个状态都需要什么。在您的情况下,您的容器需要 state.bookDetail
。
希望对您有所帮助。
关于javascript - 为什么我的 Container 组件从其他 reducer 获取状态对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47827439/