React 上下文总是 returns EMPTY
React Context always returns EMPTY
我有一个 Search
父组件和一个 SideBar
子组件,我试图在 SideBar
中获取上下文,但每次它 returns 都是空的。
我完全按照教程进行操作:https://itnext.io/manage-react-state-without-redux-a1d03403d360
但它从来没有奏效,有人知道我做错了什么吗?
这里是项目的codesandbox link:https://codesandbox.io/s/vigilant-elion-3li7v
您将商店作为道具传递,因此要访问它,您需要在 SideBar
中输入 this.props.store
。
不是this.state.store
围绕搜索和边栏创建一个包装应用程序组件:
const App = props => (
<div>
<Search />
<SideBar />
</div>
);
export default createStore(App);
现在您可以使用 set 操作状态,并获取您在子组件搜索和边栏中可用的状态。
在搜索组件中你可以有类似的东西:
componentDidMount() {
this.props.store.set("showModal", this.state.showModal);
}
也用 withStore(Search) ofc 包装。
现在您可以在边栏中调用:
render() {
return (
<div>
{"Sidebar: this.state.store: ---> " +
JSON.stringify(this.props.store.get("showModal"))}
}
</div>
);
}
你会得到输出。
那篇文章是我写的。
解决您的具体问题:
当使用 HOC withStore
时,您正在将 prop store
注入包装组件:<WrappedComponent store={context}
。
prop store
的值是一个包含 3 个函数的对象:get
、set
和 remove
.
因此,与其打印它,不如使用它。例如 this.props.store.get("currentAlbums")
或 this.props.store.set("currentAlbums", [album1, album2])
.
此示例由您的代码分叉:https://codesandbox.io/s/nameless-wood-ycps6
不过
不要重写文章代码,而是使用库:https://www.npmjs.com/package/@spyna/react-store,已经打包,测试,并且有更多的特性。
一个更好的解决方案是使用这个库:https://www.npmjs.com/package/react-context-hook。那是那篇文章中那个的新版本。
这是更新另一个组件内容的边栏示例:https://codesandbox.io/s/react-context-hook-sidebar-xxwkm
使用react上下文时要小心API
使用 React 上下文 API 管理应用程序的全局状态存在一些性能问题,因为每次上下文更改时,每个子组件都会更新。
所以,我不建议将它用于大型项目。
我有一个 Search
父组件和一个 SideBar
子组件,我试图在 SideBar
中获取上下文,但每次它 returns 都是空的。
我完全按照教程进行操作:https://itnext.io/manage-react-state-without-redux-a1d03403d360 但它从来没有奏效,有人知道我做错了什么吗?
这里是项目的codesandbox link:https://codesandbox.io/s/vigilant-elion-3li7v
您将商店作为道具传递,因此要访问它,您需要在 SideBar
中输入 this.props.store
。
不是this.state.store
围绕搜索和边栏创建一个包装应用程序组件:
const App = props => (
<div>
<Search />
<SideBar />
</div>
);
export default createStore(App);
现在您可以使用 set 操作状态,并获取您在子组件搜索和边栏中可用的状态。
在搜索组件中你可以有类似的东西:
componentDidMount() {
this.props.store.set("showModal", this.state.showModal);
}
也用 withStore(Search) ofc 包装。
现在您可以在边栏中调用:
render() {
return (
<div>
{"Sidebar: this.state.store: ---> " +
JSON.stringify(this.props.store.get("showModal"))}
}
</div>
);
}
你会得到输出。
那篇文章是我写的。
解决您的具体问题:
当使用 HOC withStore
时,您正在将 prop store
注入包装组件:<WrappedComponent store={context}
。
prop store
的值是一个包含 3 个函数的对象:get
、set
和 remove
.
因此,与其打印它,不如使用它。例如 this.props.store.get("currentAlbums")
或 this.props.store.set("currentAlbums", [album1, album2])
.
此示例由您的代码分叉:https://codesandbox.io/s/nameless-wood-ycps6
不过
不要重写文章代码,而是使用库:https://www.npmjs.com/package/@spyna/react-store,已经打包,测试,并且有更多的特性。
一个更好的解决方案是使用这个库:https://www.npmjs.com/package/react-context-hook。那是那篇文章中那个的新版本。
这是更新另一个组件内容的边栏示例:https://codesandbox.io/s/react-context-hook-sidebar-xxwkm
使用react上下文时要小心API
使用 React 上下文 API 管理应用程序的全局状态存在一些性能问题,因为每次上下文更改时,每个子组件都会更新。 所以,我不建议将它用于大型项目。