这是一个名为FrankerZ:的用户的示例代码
class ExampleComponent extends React.Component {
onBlur = async () => {
const results = await axios.get('myhttpendpoint');
this.setState({
results
});
}
render() {
return (
<div>
<form>
<span className="name"> Search Term: </span>
<input id="search-term" value={this.state.value} onBlur={this.onBlur} />
</form>
<div id="results">
{this.state.results}
</div>
</div>)
}
}
但本质上,我的问题是,如果我的axios.get返回了一个带有之类密钥的对象,会怎么样
[{name:test1,data:datadatadata},{name:test2,data:data
如何在每个对象自己的span或div中渲染它?我试着使用这样的地图
this.setState(results.map((item, index) => (<li key = {index}>{item.name}</li>)));
但它似乎不起作用。我这样做是因为React似乎无法用键渲染对象,它告诉我使用数组,这就是我尝试的。
您应该在render方法或任何其他方法中执行map
,并在render中调用它,但不能在set状态下调用它。
像这样的
class ExampleComponent extends React.Component {
onBlur = async () => {
const results = await axios.get('myhttpendpoint');
this.setState({
results
});
}
render() {
return (
<div>
<form>
<span className="name"> Search Term: </span>
<input id="search-term" value={this.state.value} onBlur={this.onBlur} />
</form>
<div id="results">
{this.state.results.map(item => (<li key={item.name}>{item.name}</li>))}
</div>
</div>)
}
}
标记不应进入状态。
render((应该是这样的。
<div id="results">
<ul>
{
this.state.results.map((item, index) => <li key = {index}>{item.name}</li>)
}
</ul>
</div>
确保在构造函数中像这样初始化状态。
this.state = {
results : []
};
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
state = {
frank: [] // Basically, you will have a place in the state where you will save your data, which is empty.
}
componentDidMount(){
// This lifecycle method is used to fire requests.
// Fire your request.
// get the response.
// save the data only in the state, don't save ELEMENTS such like li.
const _result = [
{ id: 1, name: 'Frank1' },
{ id: 2, name: 'Frank2' }
];
this.setState({
frank: _result
});
}
render() {
const { frank } = this.state;
return (
<div>
<form>
<span className="name"> Search Term: </span>
<input id="search-term" value={this.state.value} onBlur={this.onBlur} />
</form>
<div id="results">
{/*HERE DO MAPPING*/}
{
frank.map((item, index) => <li key={index}>{item.name}</li>)
}
</div>
</div>)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
关注上面的评论。现场演示:https://codesandbox.io/s/kxv6myl8wo