【发布时间】: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