Coo*_*oop 12 javascript reactjs next.js
我有一个无状态的功能组件,它没有道具并从 React 上下文填充内容。作为参考,我的应用程序使用 NextJS 并且是一个同构应用程序。我第一次尝试在这个组件上使用 React.memo() 但它会在客户端页面更改时不断重新渲染,尽管道具和上下文没有改变。由于我放置了控制台日志,我知道这一点。
我的组件的一个简短示例是:
const Footer = React.memo(() => {
const globalSettings = useContext(GlobalSettingsContext);
console.log('Should only see this once');
return (
<div>
{globalSettings.footerTitle}
</div>
);
});
Run Code Online (Sandbox Code Playgroud)
我什至尝试过在没有运气的情况下传递第二个参数:
const Footer = React.memo(() => {
...
}, () => true);
Run Code Online (Sandbox Code Playgroud)
任何想法这里出了什么问题?
编辑:上下文提供程序的用法_app.js如下所示:
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
...
return { globalSettings };
}
render() {
return (
<Container>
<GlobalSettingsProvider settings={this.props.globalSettings}>
...
</GlobalSettingsProvider>
</Container>
);
}
}
Run Code Online (Sandbox Code Playgroud)
实际的 GlobalSettingsContext 文件如下所示:
class GlobalSettingsProvider extends Component {
constructor(props) {
super(props);
const { settings } = this.props;
this.state = { value: settings };
}
render() {
return (
<Provider value={this.state.value}>
{this.props.children}
</Provider>
);
}
}
export default GlobalSettingsContext;
export { GlobalSettingsConsumer, GlobalSettingsProvider };
Run Code Online (Sandbox Code Playgroud)
小智 11
问题来自useContext. 每当您的上下文中的任何值发生更改时,无论您使用的值是否已更改,组件都会重新渲染。
解决方案是withMyContext()像这样创建一个 HOC(即);
// MyContext.jsx
// exported for when you really want to use useContext();
export const MyContext = React.createContext();
// Provides values to the consumer
export function MyContextProvider(props){
const [state, setState] = React.useState();
const [otherValue, setOtherValue] = React.useState();
return <MyContext.Provider value={{state, setState, otherValue, setOtherValue}} {...props} />
}
// HOC that provides the value to the component passed.
export function withMyContext(Component){
<MyContext.Consumer>{(value) => <Component {...value} />}</MyContext.Consumer>
}
// MyComponent.jsx
const MyComponent = ({state}) => {
// do something with state
}
// compares stringified state to determine whether to render or not. This is
// specific to this component because we only care about when state changes,
// not otherValue
const areEqual = ({state:prev}, {state:next}) =>
JSON.stringify(prev) !== JSON.stringify(next)
// wraps the context and memo and will prevent unnecessary
// re-renders when otherValue changes in MyContext.
export default React.memo(withMyContext(MyComponent), areEqual)
Run Code Online (Sandbox Code Playgroud)
将上下文作为道具传递而不是在渲染中使用它允许我们使用 areEqual 隔离我们真正关心的变化值。在渲染期间无法进行这种比较useContext。
我会大力提倡将选择器作为第二个参数,类似于 react-redux 的新钩子 useSelector。这将允许我们做类似的事情
const state = useContext(MyContext, ({state}) => state);
谁的返回值只会在状态改变时改变,而不是整个上下文。
但我只是一个梦想家。
这可能是我现在对简单应用程序使用 react-redux 而不是钩子的最大论点。
| 归档时间: |
|
| 查看次数: |
6996 次 |
| 最近记录: |