javascript - 使用 axios 渲染 redux 操作时未捕获的 Promise

标签 javascript reactjs redux

您好,我在尝试渲染 json 响应时使用 redux 来执行一些 API 调用。我正在尝试记录响应以弄清楚发生了什么,但即使这样也不起作用?

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

这是在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);

以下是完整的错误消息:

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)

我的请求是否有错误?或者我如何呈现响应?从我的 API 日志来看,似乎没有收到任何信息?如果我没有提供足够的信息,请道歉

最佳答案

这里的错误是您在返回的 JSX 标记中调用 loadyield() 函数

组件安装后即可加载数据。您可以通过添加 componentDidMount() 生命周期方法来完成此操作。所以你的 DashContent 看起来像这样。

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

或者,您可以使用 componentWillRecieveProps (此生命周期方法已被弃用。可以像 this 一样替换它),或者只是使用一个刷新按钮来调度更新 yield 的操作。

关于javascript - 使用 axios 渲染 redux 操作时未捕获的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868320/

相关文章:

javascript - 从 AngularJS 格式化指令监听父模型的变化

javascript - 如何使用 webpack 加载库源映射?

javascript - 如何使用 Hooks 将状态从 child 传递给 parent

javascript - Mediarecorder : How to support audio recording on Safari, IE 11?

javascript - 如何检查 JavaScript 中函数返回的内容?

javascript - X 轴刻度不以 highcharts 中的列系列为中心(jsFiddle)

javascript - 如何基于 javascript/typescript 中的另一个数组创建动态数组?

ReactJS Material UI 字体图标设置大小

reactjs - 错误: Unable to find element with ID 275

node.js - 在 react 中从数据库获取数据的正确方法是什么?