我有一个使用react路由器在客户端呈现的react组件。我有一个redux存储,它在调度后被成功填充(因此我相信操作和reducer工作正常(
当connect-mapStateToProps函数启动时,状态为空,就会出现问题。
我已经订阅了store和console.log(store.getState(((,我可以看到状态设置正确。
我哪里错了?
class MyComponent extends Component {
componentWillMount(){
this.props.fetchData();
}
render(){
console.log(this.props);
return(<div>{this.props}</div>
}
const mapStateToProps = (state) => {
console.log(state); //This is empty e.g. { form : {} }
return {
formJSON: state.form
}
};
const mapDispatchToProps = { fetchData};
export default connect( mapStateToProps, mapDispatchToProps )(MyComponent);
反应路由器的东西
class ClientApp extends Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<Switch>
<Route exact path="/" >
<div>Root</div>
</Route>
<Route path='/mycomponent'>
<Container fluid>
<Row>
<Col lg={2}>
<MyComponent/>
</Col>
<Col lg={7}>
<OtherComponent />
</Col>
<Col>
<YetAnotherComponent/>
</Col>
</Row>
</Container>
</Route>
</Switch>
</Router>
</Provider>
);
}
}
export default ClientApp;
你能试试这个吗:
import React from "react";
import "./cart-icon.styles.scss";
import { connect } from "react-redux";
import { fetchData } from "path for fetchData";
class MyComponent extends Component {
constructor(props){
super(props);
this.state={
formJSON:{}
}
}
componentDidMount(){
this.props.fetchData();
}
componentDidUpdate(prevProps){
if(prevProps.formJSON !==this.props.formJSON){
this.setState({formJSON})
}
}
render(){
console.log(this.state.formJSON);
return(<div>{this.state.formJSON}</div>
}}
const mapStateToProps = ({form}) => ({
formJSON:form
});
const mapDispatchToProps = (dispatch) => ({
fetchData: () => dispatch(fetchData()),
});
export default connect( mapStateToProps, mapDispatchToProps )(MyComponent);