【问题标题】:React Context always returns EMPTYReact Context 总是返回 EMPTY
【发布时间】:2020-09-30 11:23:01
【问题描述】:

我有一个Search 父组件和一个SideBar 子组件,我试图在SideBar 中获取上下文,但每次它都返回空。

我完全按照教程进行操作:https://itnext.io/manage-react-state-without-redux-a1d03403d360 但它从来没有奏效,有人知道我做错了什么吗?

这里是项目的代码框链接:https://codesandbox.io/s/vigilant-elion-3li7v

【问题讨论】:

  • 我不知道你做了什么,但这里有一个你使用的 toturial 的工作示例......从那里开始......codesandbox.io/s/o2w7ojw3z?from-embed=&file=/src/…
  • 我使用了 Spyna 的 HOC 辅助函数,与他编写的代码完全一样,但它不起作用

标签: reactjs react-redux react-context


【解决方案1】:

那篇文章是我写的。

解决您的具体问题:

当使用 HOC withStore 时,您将 store 注入到包装组件中:<WrappedComponent store={context}。 属性 store 的值是一个包含 3 个函数的对象:getsetremove

因此,您应该使用它,而不是打印它。例如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

使用反应上下文 API 时要小心

使用 React Context API 管理应用程序的全局状态存在一些性能问题,因为每次上下文更改时,每个子组件都会更新。 所以,我不建议将它用于大型项目。

图书馆https://www.npmjs.com/package/@spyna/react-store 有这个问题。

https://www.npmjs.com/package/react-context-hook 没有。

【讨论】:

【解决方案2】:

您将商店作为道具传递,因此要访问它,您需要 this.props.store 在您的 SideBar 中。

不是this.state.store

【讨论】:

  • 你好,谢谢回复,我已经改成this.props.store,但是还是返回{}
  • @yelnn 不确定您要做什么,但 store 一开始只有 3 种方法。您无法访问 Search 本地状态,只能访问存储状态。
  • 您很可能希望使用与Search 组件分离的提供程序,并在Search 组件上使用withStore。您很可能希望将共享状态移至store
  • 最后请记住,使用JSON.stringify时不包含函数
  • 我明白了,我正在尝试获取Search 组件的state 数据,例如this.props.store.get('something')SideBar 子组件中
【解决方案3】:

围绕搜索和侧边栏创建一个包装 App 组件:

const App = props => (
  <div>
    <Search />
    <SideBar />
  </div>
);
export default createStore(App);

现在您可以使用 set 操作状态,并在子组件 Search 和 Sidebar 中获取可用的状态。

在搜索组件中,您可以使用以下内容:

  componentDidMount() {
    this.props.store.set("showModal", this.state.showModal);
  }

也用 withStore(Search) ofc 包装。

现在可以在 SideBar 中调用:

  render() {
    return (
      <div>
        {"Sidebar: this.state.store: ---> " +
          JSON.stringify(this.props.store.get("showModal"))}
        }
      </div>
    );
  }

你会得到输出。

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 2017-12-24
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多