![](/img/trans.png)
[英]React.js component run error.Uncaught TypeError: Cannot read property '0' of undefined
[英]React.js component run error. Uncaught TypeError: this.state.setState is not a function
我正在尝试创建Fetch
组件,该组件应发送POST
请求并返回响应内容。 我的问题是如何在App
组件中获取结果数据。 我在chrome中遇到了这样的错误:
这是我的js代码:
import React, {Component} from 'react';
import Request from 'react-http-request';
class Fetch extends React.Component {
constructor() {
super();
this.state = {postResult: ''};
}
render() {
return (
<Request
url='http://localhost:8080/path'
method='post'
accept='application/json'
type="application/json"
send='{"law":"The First Law", "character":"No.1 Character"}'
verbose={true}
>
{
({error, result, loading}) => {
if (loading) {
return <div>loading...</div>;
} else {
this.state.setState({postResult: postResult});
return <div>{JSON.stringify(result)}</div>;
}
}
}
</Request>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {test: ''};
}
render() {
this.state.setState({test: (<Fetch />)});
return (
<table>
<thead>
<tr>
{this.state.test}
</tr>
</thead>
</table>
)
}
}
ReactDOM.render(<App/>, document.getElementById('react'))
我不知道如何从Fetch
组件获取结果数据,这让我感到困扰。
而不是使用
this.state.setState({postResult: postResult});
你应该用
this.setState({postResult: postResult});
错误在您的代码片段中
if (loading) {
return <div>loading...</div>;
} else {
this.state.setState({postResult: postResult});
return <div>{JSON.stringify(result)}</div>;
}
}
}
</Request>
说明:
this
引用了Fetch
类的对象,该对象继承了React.Component
类的setState()
方法。
this.state
是一个普通对象,仅保存数据,没有要执行的功能。 (它没有setState()
)
问题出在this.state.setState({postResult:postResult});
this.setState表示您正在将当前状态修改为在this.setState函数中更新的新值。
this.state.setState永远不会被调用,因为状态对象不提供任何此类功能,因此请将其更改为this.setState
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.