Reactjs 当我按react中的fetch按钮时,对象数组未被提取
我在运行此命令时出错!!它表示无法读取未定义映射的属性。我想在按下buton时运行fetch函数!然后,对象将显示。。但似乎没有什么是那样的。。它会出错Reactjs 当我按react中的fetch按钮时,对象数组未被提取,reactjs,dictionary,undefined,fetch,Reactjs,Dictionary,Undefined,Fetch,我在运行此命令时出错!!它表示无法读取未定义映射的属性。我想在按下buton时运行fetch函数!然后,对象将显示。。但似乎没有什么是那样的。。它会出错 class App extends React.Component { constructor(props) { super(props); this.state = { robots: [] } this.fetchData = this.fet
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
robots: []
}
this.fetchData = this.fetchData.bind(this);
}
//fetch data function . linked with button shdfvjksvda kvahsdksa
fetchData=()=> {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => { response.json() })
.then((data) => {
console.log(data);
this.setState({ robots: data })
}
)
;
}
render() {
return (
<div>
<button onClick={this.fetchData}>Fetch</button>
<p>
{this.state.robots.map(el => {
return <div key={el.id}>
<span>{el.email}</span>
<span>{el.name}</span>
<span>{el.id}</span>
</div>
})}
</p>
</div>
)
}
}
havscjhuvsakdvasdu
export default App;
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
机器人:[]
}
this.fetchData=this.fetchData.bind(this);
}
//获取数据功能。与按钮shdfvjksvda kvahsdksa链接
fetchData=()=>{
取('https://jsonplaceholder.typicode.com/users')
.then(response=>{response.json()})
。然后((数据)=>{
控制台日志(数据);
this.setState({robots:data})
}
)
;
}
render(){
返回(
取来
{this.state.robots.map(el=>{
返回
{el.email}
{el.name}
{el.id}
})}
)
}
}
havscjhuvsakdvasdu
导出默认应用程序;
链接承诺时,您错过了返回语句
fetchData=()=> {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => { return response.json() })
.then((data) => {
console.log(data);
this.setState({ robots: data })
}
)
;
}
您在链接承诺时错过了返回声明
fetchData=()=> {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => { return response.json() })
.then((data) => {
console.log(data);
this.setState({ robots: data })
}
)
;
}
正如Easwar所指出的,您没有从第一个
.then()
返回任何内容。然而,理想的解决方案是省略{括号,让它自动返回值
fetchData = () => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then((data) => {
console.log(data);
this.setState({ robots: data })
});
}
箭头函数可以有“简明体”或通常的“块体”
在简明体中,只指定一个表达式,该表达式将成为隐式返回值。在块体中,必须使用显式返回语句
有关它们如何工作的更多信息,请参见。正如Easwar指出的,您没有从第一个
.then()
返回任何内容。理想的解决方案是省略{
括号,让它自动返回值。这更简洁,可读性更强:
fetchData = () => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then((data) => {
console.log(data);
this.setState({ robots: data })
});
}
箭头函数可以有“简明体”或通常的“块体”
在简明体中,只指定一个表达式,该表达式将成为隐式返回值。在块体中,必须使用显式返回语句
有关它们如何工作的更多信息,请参阅。我猜是
.then(response=>{response.json()}
行。在本例中,您的意思是执行response.json()
,而不对其进行任何操作(或为下一个然后
返回任何内容)。我建议在这里处理setState
,例如。然后(response=>{this.setState({robots:response.json()})
我猜是。然后(response=>{response.json()}
行。在这种情况下,您的意思是执行response.json()
,而不进行任何操作(或者为下一个然后返回任何内容)。我建议在这里处理setState
,例如。然后(response=>{this.setState({robots:response.json()})
是的,谢谢Frankerz!你只要解决我的问题,我省略了{}括号和代码已经运行了。是的,谢谢你,弗兰克兹!你刚刚解决了我的问题,我省略了{}括号,代码已经运行了。