mapStateToProps
是 Redux 中的一个函数,它用于将 Redux store 中的状态映射到 React 组件的 props 上。当 Redux store 中的状态发生变化时,mapStateToProps
会重新执行,React 组件会接收到新的 props 并重新渲染。如果你发现组件在状态更改时不更新,可能是以下几个原因造成的:
connect
函数将组件与 Redux store 连接起来。connect
函数将组件与 Redux store 连接起来。immer
或者扩展运算符。immer
或者扩展运算符。React.PureComponent
或者实现了 shouldComponentUpdate
方法,那么它可能会跳过不必要的渲染。确保 shouldComponentUpdate
返回 true
当 props 或 state 发生变化时。mapStateToProps
很复杂或者计算开销很大,可以使用 Reselect 库来创建记忆化的选择器,这样只有在相关状态变化时,选择器才会重新计算。mapStateToProps
很复杂或者计算开销很大,可以使用 Reselect 库来创建记忆化的选择器,这样只有在相关状态变化时,选择器才会重新计算。shouldComponentUpdate
,可以避免不必要的渲染,提高应用性能。假设我们有一个简单的计数器应用,我们想要在 Redux store 中更新计数器的值,并让组件重新渲染。
// actions.js
export const increment = () => ({
type: 'INCREMENT'
});
// reducer.js
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
}
// Counter.js
import React from 'react';
import { connect } from 'react-redux';
import { increment } from './actions';
const Counter = ({ count, increment }) => (
<div>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</div>
);
const mapStateToProps = (state) => ({
count: state.count
});
export default connect(mapStateToProps, { increment })(Counter);
在这个例子中,每次点击按钮,increment
动作会被触发,reducer 会返回一个新的状态对象,mapStateToProps
会检测到状态的变化,并使 Counter
组件重新渲染。
如果你遇到了组件不更新的问题,请检查以上提到的几个方面,通常可以找到并解决问题。
没有搜到相关的文章