从 redux-saga 函数访问 React 上下文值 [英] Access React context value from redux-saga function
问题描述
我有一些变量由 React Context 通过 React.createContext() 和 Provider 和 Consumer 组件控制.我也在使用 redux-saga,所以我的问题是无论如何都可以在 redux-saga 函数中访问这个上下文值.我正在寻找类似于 redux-store 的yield select"语句.
I have some variables which are controlled by React Context through React.createContext() with Provider and Consumer component. I'm also using redux-saga, so my question is are there anyway to access this context value in redux-saga function. I'm looking for something like "yield select" statement that works with redux-store.
知道的人请给我解释一下.提前谢谢你.
Anyone who know it please explain to me. Thank you in advances.
P/S:目前,我在分派动作时将上下文值传递给动作对象负载.所以在 redux-saga 中,我们可以在 action 参数中使用它.我不知道这是否是最佳做法.
P/S: Currently, I pass context value to action object payload when dispatch an action. So in redux-saga, we can use it in action parameter. I don't know whether it's the best practice.
推荐答案
现在有一个包可以让您轻松获取上下文,react-outside-call
您可以保留提供程序组件的外部引用,并从中获取状态.
You can keep an outside reference of your provider component, and grab the state from that.
这样的东西...
提供者组件
class AppProvider extends Component {
state = {
number: 10,
}
render() {
return (
<AppContext.Provider value={this.state}>
{this.props.children}
</AppContext.Provider>
)
}
}
Apps 主入口文件,或您引用该提供程序实例的任何地方.
Apps main entry file, or where ever you reference that provider instance.
let appProviderRef
export const getProviderState = () => appProviderRef.state
ReactDOM.render(
<AppProvider ref={ref => appProviderRef = ref}>
<App />
</AppProvider>
, document.getElementById('root'))
您现在可以同步调用 getProviderState
这篇关于从 redux-saga 函数访问 React 上下文值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!