【发布时间】:2016-12-15 22:58:12
【问题描述】:
试图理解 React-Redux,我发现当状态的任何部分发生变化时,我的所有组件都会获得新的 props,这很不寻常。那么这是设计使然还是我做错了什么?
示例应用
class App extends React.Component {
render(){return (
<div>
<Navbar data={this.props.navbar} />
<Content data={this.props.content} />
</div>);
}
}
select (state) => ({ navbar:state.navbar, content:state.content});
export default connect(select)(App);
组件
export const NavbarForm = props => {
console.log('RENDERING with props--->',props);
return (<h1>NAV {props.data.val}</h1>);
};
export const ContentForm = props => {
console.log('RENDERING CONTENT with props--->',props);
return (<h1>CONTENT {props.data.val}</h1>);
};
////////INDEX.js//////
const placeholderReducer = (state={val:0},action)=>{
//will update val to current time if action start with test/;
if(action.type.indexOf('TEST/') === 0)return {val:Date.now();}
return state;
}
export const rootReducer = combineReducers({
navbar:placeholderReducer,
content: (state,action)=>(state || {}), //**this will never do a thing.. so content should never updates right !!**
});
const store = createStore(rootReducer, {}, applyMiddleware(thunk));
render( <Provider store={store}> <App /></Provider>, document.getElementById('app')
);
setInterval(()=>{ store.dispatch(()=>{type:'TEST/BOOM'}) },3000);
好的,在这个应用程序中,我期望导航栏组件将每 3000 毫秒更新一次,而内容组件将永远不会更新,因为它的减速器将始终返回相同的状态。
但我发现每次触发动作时两个组件都会重新渲染,这真的很奇怪。
这是设计使然吗?如果我的应用有 100 多个组件,我应该担心性能吗?
【问题讨论】:
-
您的应用在性能方面无法很好地扩展,但我会回答您的主要问题。将您的导航栏功能组件转换为基于类的组件并添加生命周期方法
componentWillReceiveProps(nextProps)然后设置您的状态...要了解更多信息,请阅读here -
@AdegbuyiAdemola 为什么它不会扩展?这不是 redux 文档中提出的结构吗?你能详细说明:)吗?添加生命周期将如何阻止 react-redux 更新道具?
-
如果存储出现问题,您可能会遇到最大堆栈超出错误。我没有说添加生命周期会阻止 react-redux ......我的意思是,你也应该在 Navbar 上使用它并使 Navbar 成为基于类的组件
-
请记住,在 React 中
render并不一定意味着更改 DOM。这意味着运行渲染算法来检查 DOM 是否需要更新。所以render操作可能是亚毫秒级的。另外,请查看新的React.PureComponent
标签: reactjs redux flux react-redux