[英]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.