如何解决将道具从redux存储传递到子组件
我试图避免在每个需要访问它的组件中手动订阅redux存储。意思是,我想避免在每个需要访问存储的组件中执行connect(mapStatetoProps,mapdispatchToProps)(component)
。我目前的策略是拥有一个App.js组件:
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as AllStudentActions from '../actions/StudentActions';
import * as AllEmployerActions from '../actions/EmployerActions';
import * as AllRecruiteractions from '../actions/Recruiteractions';
import * as AllUserActions from '../actions/UserActions';
import * as AllSocketActions from '../actions/SocketActions';
class App extends React.Component {
render() {
return (
<div>
<h1>This is app</h1>
{/* {React.cloneElement(this.props.children,this.props)} */}
{/* {React.cloneElement({...this.props}.children,{...this.props})} */}
{React.cloneElement({...{...this.props}.children}.children,{...this.props})}
</div>
)
}
}
const mapStatetoProps = (state) => {
return {
jobs: state.jobs,employers: state.employers,recruiters: state.recruiters,user: state.user,students: state.students,socket: state.socket
};
}
const mapdispatchToProps = (dispatch) => {
return {
actions: {
userActions: bindActionCreators(AllUserActions,dispatch),studentActions: bindActionCreators(AllStudentActions,employerActions: bindActionCreators(AllEmployerActions,socketActions: bindActionCreators(AllSocketActions,recruiteractions: bindActionCreators(AllRecruiteractions,dispatch)
}
};
}
export default connect(mapStatetoProps,mapdispatchToProps)(App);
那是使用React.cloneElement基本上将redux存储中的props放到子组件中。我是从Wess Bos的redux教程(https://www.youtube.com/watch?v=l2IOqeubsBw&t=388s&ab_channel=WesBos)中得到这个想法的。
但是,我也在使用react路由器,如我的index.js所示:
import React from 'react';
import { render } from 'react-dom';
import App from './components/App';
import WaveyText from './components/WaveyText';
import Main2 from './components/Main2';
// import pages components
// router dependencies
import { Route,Switch } from 'react-router';
import { browserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store';
const router = (
<Provider store={store}>
<browserRouter>
<Route path="/" component={App}>
<Switch>
<Route exact path="/" component={WaveyText}></Route>
<Route exact path= "/test"> <div> Test </div> </Route>
</Switch>
</Route>
</browserRouter>
</Provider>
)
render(router,document.getElementById('root'));
和传递到Route的组件未连接到商店。至少,App.js应该呈现,并且在react dev工具中,我应该看到App.js组件中redux存储的默认状态,但这没有发生。显然,App.js下的子组件也未连接。
我不确定这是否与我使用React Router或在App.js中封装组件的技术有关。
非常感谢您的帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。