gpt4 book ai didi

javascript - 对象在 React 中无效

转载 作者:行者123 更新时间:2023-12-03 04:59:57 24 4
gpt4 key购买 nike

这是我的 app.js

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'

const App = ({ children }) => (
<div>
{children}
</div>
)

import Index from './index'
import Weatherhbh from './weatherhbh'

render((
<Router history={browserHistory}>
<Route path="widget/" component={App}>
<IndexRoute component={Index}/>
<Route path="hbh/" component={Weatherhbh}/>
</Route>
</Router>
), document.getElementById('app'))

这是我的 hbh 组件

import React from 'react'
import axios from 'axios'

const urlP=`/hourly`;

export default class App extends React.Component {
constructor(props){
super(props);
this.state={
data:[]
};
}
componentDidMount() {
axios.get(urlP)
.then(response => {
console.log(response.data,"this is response")
this.setState({
data:response
});
});
}


render() {
return( <div>

<p>{this.state.data}</p>

</div>
)
}
}

我收到此错误

bundle.js:1244 Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of App.(…)

如何修复它以便我可以显示来自后端的所有数据?

最佳答案

this.setState({
data:response
});

这部分代码将响应(一个对象)分配给状态变量data,然后:

  <p>{this.state.data}</p>

也尝试渲染对象,但 react 不知道如何渲染对象。要获取您的数据,请使用:

<p>{this.state.data.data}</p>

现在 data=response 和 axios 响应有一个名为 data 的属性,它保存实际数据。如果万一数据也是一个对象(json 数据),您将必须访问特定的键,例如

this.state.data.data.username

关于javascript - 对象在 React 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42271468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com