我正在尝试创建一个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
对象的引用类,继承 setState()
方法来自React.Component
类。
this.state
是一个普通对象,仅保存数据,没有要执行的函数。 (它没有 setState()
)
关于javascript - React.js 组件运行错误。未捕获的 TypeError : this. state.setState 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45852770/