报错:
could not find react-redux context value; please ensure the component is wrapped in a <Provider>
问题:
PS 如果和你遇到问题不一样,就没必要继续看了。
组件库是 Ant Design Mobile,这个组件有个指令组件 Modal(弹窗),它的 content属性支持渲染React.ReactNode。So,当我给它传入自定义组件 SuccessorModalContent 的时候,它报错了上面提示。
Modal.show({
content: <SuccessorModalContent onLogin={onGotoLogin} onRegister={nextGoRegister} />,
className:'dialog-registr-custom',
closeOnMaskClick: true,
})
解决:HOC
- 创建一个Hoc组件,
@/components/hoc/withStore.jsx,引入和 跟App组件一样拥有的 store和 Provider;
import React from 'react';
import { Provider } from 'react-redux'
import store from '@/store/index.js'
const withStore = (Component)=>{
return class WithStoreComponents extends React.Component {
state = {
}
render(){
return (
<Provider store={store}>
<Component {...this.props} />
</Provider>)
}
}
}
export default withStore;
- 在自定义组件中,使用Hoc组件进行包装,便可以解决这个问题
import withStore from '@/components/hoc/withStore.jsx'
import { useDispatch, useSelector } from 'react-redux';
function SuccessorModalContent(props) {
{/* 这样便可以正常使用useSelector等hooks */}
const { registerEnterpriseList,registerForm } = useSelector(state => {
return state.commonRegister;
});
return (<div>
{/* some code ... */}
</div>
)
}
export default withStore(SuccessorModalContent);