【问题标题】:Access context outside render tree访问渲染树外的上下文
【发布时间】:2022-04-21 23:02:15
【问题描述】:

我在 React Native 中有一个使用许多上下文的应用程序。我想在非渲染函数中访问其中一个,例如:

const DataContext = React.createContext();

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // ...
      systemState: {},
      // ...
    };
  }

  componentDidMount() {
    const systemState = offlineSystemState();
    this.setState(systemState);
  }

  //   ...

  render() {
    return (
      <DataContext.Provider value={this.state}>
        <CustomComponent />
      </DataContext.Provider>
    );
  }
}

// OfflineSystemState component wants access to the DataContext,
// but impossible because it is not being rendered.
// Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
const offlineSystemState = () => {
  const context = useContext(DataContext);

  const systemState = processData(context.data);

  return systemState;
};

可以这样做吗?如果没有,是否有商店可以做到(Redux,Mobx,...)?

谢谢。

【问题讨论】:

    标签: javascript reactjs react-native react-context


    【解决方案1】:

    经过一年多的寻找解决方案,我的结论是根本不可能。

    唯一的解决方案是直接将依赖传递给非渲染服务和上下文以共享一个依赖实例。

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 2015-01-02
      • 2014-11-03
      • 2012-09-21
      相关资源
      最近更新 更多