我正在尝试获取数据,将其置为状态然后进行修改
state = {
data: []
}
我的状态为空数组,然后从API获取数据
constructor(){
super();
this.getItem();
}
getItem(){
this.service
.mergeData()
.then((body) => {
this.setState({
data: body.map(product => product),
})
})
}
然后我尝试从状态使用此数据:
dataToFilter = this.state.data.map((e) => {
return e;
})
但是问题是dataToFilter为空,因为状态为空 我该怎么解决?
答案 0 :(得分:2)
编辑: OP询问了以下问题,因此我更新了StackSnippet来反映该问题。
我需要使用状态数据,而不是在render函数中,而是在componentDidMount之后的组件中使用。我能做到吗?
如果要在组件安装后加载数据,可以使用componentDidMount
生命周期方法。您可以阅读有关生命周期方法here和here的更多信息。
此外,如果您不将方法绑定到构造函数中,则需要将arrow function
与getItem()
一起使用。{em> 。 >
CodePen showing如何通过箭头函数在构造函数中使用类方法。
CodePen showing如何在构造函数中使用bind
使用类方法而没有箭头功能。
以下是使用componentDidMount
来检索API数据的方法:
class ApiFetcher extends React.Component {
state = {
apiData: "",
id: 1
};
componentDidMount() {
this.getNextFromApi();
}
getNextFromApi = () => {
fetch(`https://jsonplaceholder.typicode.com/todos/${this.state.id}`)
.then(response => response.json())
.then(json => {
this.setState({
id: this.state.id + 1,
apiData: json
}, () => {
// After you set your state,
// you can use the callback that `setState` provides
this.doSomethingWithData();
});
});
}
doSomethingWithData = () => {
// Here is where you can do something with the data
this.setState({ message: 'Check your console!' });
console.log("I am doing something with the data!", this.state.apiData);
// Do whatever you need to here
}
render() {
return (
<div>
{this.state.message ? <p>{this.state.message}</p> : ""}
<hr /><br /><br />
<h3>Just pretend this does not exist, if you do not want to display data here</h3>
<button onClick={this.getNextFromApi}>Next Result</button>
{this.state.apiData ? (
<pre>{JSON.stringify(this.state.apiData, null, 2)}</pre>
) : (
<p>Unable to get data..</p>
)}
</div>
);
}
}
class App extends React.Component {
render() {
return <ApiFetcher />;
}
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
答案 1 :(得分:0)
我认为更好,您可以使用componentwillupdate方法来调用dataToFilter。 要么 此代码调用render方法。
dataToFilter = this.state.data.map((e) => {
return e;})