Using query get JSON and use it in my React component
我正在尝试通过我的 React 组件中的 Jquery $.getJSON 函数访问 JSON 数据,但我不断收到此错误:
Invariant Violation: Minified React error #31; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Busername%2C%20img%2C%20alltime%2C%20recent%2C%20lastUpdate%7D&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
Objects are not valid as a React child (found: object with keys {username, img, alltime, recent, lastUpdate}).
这是我的代码。不太清楚问题出在哪里…..
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Board extends React.Component {
constructor(props) { super(props); this.state = { first: ”, second: ” } } componentDidMount() { var self = this; $.getJSON("https://fcctop100.herokuapp.com/api/fccusers/top/recent",function(data){ self.setState({first:data}); console.log(this.state.first); }); } render() { return ( [cc]{this.state.first} |
1
|
{this.state.second}
|
)
}
}
ReactDOM.render(
[/cc]
您不能渲染对象数组。 React 知道如何渲染组件。
一种解决方案是映射来自 XHR 响应的数组,并渲染每个对象。
你的渲染函数应该是这样的:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Board extends React.Component {
constructor(props) { super(props); this.state = { first: [], second: [] } } componentDidMount() { var self = this; $.getJSON("https://fcctop100.herokuapp.com/api/fccusers/top/recent",function(data){ console.log(data) self.setState({first:data}); }); } render() { return ( {this.state.first.map((el, i) => [cc]{JSON.stringify(el, null, ‘ ‘)} |
)}
)
}
}
ReactDOM.render(
[/cc]
另请注意,我已将初始状态更改为空数组(以便能够对其进行映射)
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/268746.html