您好,我在尝试渲染 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/