简体   繁体   English

React-Redux Connect 接收到空状态

[英]React-Redux Connect receives empty state

I have a react component being rendered client side using react router.我有一个使用反应路由器呈现客户端的反应组件。 I have a redux store that is being successfully populated after a dispatch (thus I believe the action and reducer are working correctly)我有一个在调度后成功填充的 redux 存储(因此我相信 action 和 reducer 工作正常)

The problem comes when the connect mapStateToProps function fires, the state is empty.当 connect mapStateToProps 函数触发时,问题就出现了,状态为空。

I have subscribed to the store and console.log(store.getState()) and I can see the state getting set correctly.我已经订阅了 store 和 console.log(store.getState()) 并且我可以看到状态设置正确。

Where am I going wrong?我哪里错了?

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);

The react router stuff反应路由器的东西

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;

Can you try this:你能试试这个吗:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM