简体   繁体   中英

Uncaught Promise when rendering redux action with axois

Hi I am using redux to do some API calls when trying to render the json response. I am trying to log the responses to work out what is happening but even that is not working?

dashaction.js

export function updateyield(total){
    return{
        type:"UPDATE_YIELD",
        total: total
    }
}

export function loadyield(){
    return(dispatch)=>{
        return axios.get("localhost:5000/getallyield").then ((response) => {
            dispatch(updateyield(response.data));
            let res = response.data;
            console.log(res.data)
        })
    }
}

this is rendered in DashContent

class DashContent extends Component {

    render () {
        return(

        <div>
        {this.props.loadyield()}
        <h3> Yield</h3>
        <ul>{this.props.total}</ul>
        </div>
        );
    }

}
function mapStatetoProps(state) {
    return state
    };

export default connect(mapStatetoProps, {loadyield}) (DashContent);

Here is the full error message:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    in div (at dashboardcontainer.js:12)
    in DashContent (created by ConnectFunction)
    in ConnectFunction (at Dashboard.js:15)
    in div (at Dashboard.js:14)
    in Dashboard (created by Context.Consumer)
    in Route (at App.js:16)
    in Switch (at App.js:15)
    in div (at App.js:13)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:12)
    in App (at src/index.js:13)
    in Provider (at src/index.js:13)

Is this an error with my request? or how I am rendering the response? from my API log nothing seems to have been recieved? apologies if I have not provided enough infomation

The error here is that you are calling the loadyield() function in the returned JSX tag

You can load the data once the component mounts. You can do this by adding a componentDidMount() lifecycle method. So your DashContent Would look something like this.

class DashContent extends Component {
    componentDidMount(){
        this.props.loadyield();
    }
    render () {
        return(
        <div>
            <h3> Yield</h3>
            <ul>{this.props.total}</ul>
        </div>
        );
    }

}

function mapStatetoProps(state) {
    return state
};

export default connect(mapStatetoProps, {loadyield}) (DashContent);

Alternatively you can use componentWillRecieveProps (this lifecycle method has been deprecated. It can be replaced like this ) or simply have a refresh button which dispatches the action to update the yield.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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