Mik*_*ike 12 javascript reactjs react-router redux
我有一个简单的路由器(启动redux-router并切换react-router到消除变量).
<Router history={history}>
<Route component={Admin} path='/admin'>
<Route component={Pages} path='pages'/>
<Route component={Posts} path='posts'/>
</Route>
</Router>
Run Code Online (Sandbox Code Playgroud)
管理组件基本上只是{this.props.children}一些导航; 它不是connected组件.
Pages组件是一个connected组件,mapStateToProps()如下所示:
function mapStateToProps (state) {
return {
pages: state.entities.pages
};
}
Run Code Online (Sandbox Code Playgroud)
帖子更有趣:
function mapStateToProps (state) {
let posts = map(state.entities.posts, post => {
return {
...post,
author: findWhere(state.entities.users, {_id: post.author})
};
}
return {
posts
};
}
Run Code Online (Sandbox Code Playgroud)
然后当我加载页面或在帖子/页面路由之间切换时,我在console.log()中得到以下内容.
// react-router navigate to /posts
Admin render()
posts: map state to props
Posts render()
posts: map state to props
Posts render()
posts: map state to props
// react-router navigate to /pages
Admin render()
pages: map state to props
Pages render()
pages: map state to props
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:为什么mapStateToProps在路线变化上被多次调用?
另外,为什么一个简单的map函数mapStateToProps会导致它在Posts容器中第三次被调用?
我正在使用Redux文档中的基本logger和crashReporter中间件,并且它没有报告任何状态更改或崩溃.如果状态没有改变,为什么组件会多次渲染?
根据经验react-redux,你不应该在里面处理商店属性,mapStateToProps因为connect使用浅层检查绑定商店属性来检查diff.
要检查是否需要更新组件,请react-redux调用mapStateToProps并检查结果的第一级属性.如果其中一个更改(===相等检查),组件将使用新的props更新.在您的情况下,每次调用都会posts更改(map转换)mapStateToProps,因此您的组件会在每次更改商店时更新!
您的解决方案是仅返回商店属性的直接引用:
function mapStateToProps (state) {
return {
posts: state.entities.posts,
users: state.entities.users
};
}
Run Code Online (Sandbox Code Playgroud)
然后在您的组件中,您可以定义一个按需处理数据的函数:
getPostsWithAuthor() {
const { posts, users } = this.props;
return map(posts, post => {
return {
...post,
author: findWhere(users, {_id: post.author})
};
});
}
Run Code Online (Sandbox Code Playgroud)