ReactJS + Typescript:使用上下文属性值设置组件状态而不触发重新渲染
我对 ReactJS 比较陌生,我正在构建一个带有上下文的应用程序。在某些时候,我需要从上下文中获取其中一个值,使其可用于编辑,并且只有在提交后才更改它在上下文中的值(以避免刷新所有其他组件)。我想做这样的事情:
export default class AComponent extends Component<any, { property?: Property }> {
public constructor(props: any) {
super(props);
}
public shouldComponentUpdate(nextProps: any, nextState: { property?: Property }) {
return nextState.property !== this.state.property;
}
public render(): JSX.Element {
return (
<AContext.Consumer>
{(data) => {
// ...
this.setState({ ...this.state, property: data.property });
// ...
}}
</AContext.Consumer>
);
}
}
但即使使用 shouldComponentUpdate
检查,它仍然刷新 4 次!如果没有它,它会产生错误(达到递归限制或类似的错误)。
问题是:使用上下文属性而不更改它直到您真正想要的那一刻的正确方法是什么?
我想在构造函数中获取 Context 属性,但我发现这种形式是已弃用:
constructor(props: any, context: AContext) {
super(props, context)
}
还有其他方法吗?
I am relatively new to ReactJS and I'm building an app with a Context. At some point I need to get one of the values from the Context, make it available for editing and only after it's submitted change it's value in the Context (to avoid refreshing all the other components). I thought of doing something like this:
export default class AComponent extends Component<any, { property?: Property }> {
public constructor(props: any) {
super(props);
}
public shouldComponentUpdate(nextProps: any, nextState: { property?: Property }) {
return nextState.property !== this.state.property;
}
public render(): JSX.Element {
return (
<AContext.Consumer>
{(data) => {
// ...
this.setState({ ...this.state, property: data.property });
// ...
}}
</AContext.Consumer>
);
}
}
But even with the shouldComponentUpdate
check, it still refreshes 4 times! Without it it produces an error (recursion limit reached or something like that).
The question is: What's the correct way of working with a context property without changing it until the moment you actually want to?
I wanted to get the Context property inside the constructor but I have found that this form is deprecated:
constructor(props: any, context: AContext) {
super(props, context)
}
Is there any other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
属性不仅可以添加到上下文中,还可以向它们添加方法。
Context 旨在共享可被视为 React 组件树“全局”的数据,例如当前经过身份验证的用户、主题或首选语言
如果您想更改来自不同组件的数据,我更喜欢使用状态类似 Redux
的管理
快乐编码
not only can property add to context but you can also add methods to them.
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language
if you want to change data from different components, I prefer to use state management like Redux
happy codeing