【发布时间】:2018-01-27 11:50:21
【问题描述】:
我的问题是我有一些来自 SearchForm 组件的值。他们将正确的值作为参数传递给 handleSearch 函数,但我对 setState 的调用什么也没做。我已经包含了 console.logs 来显示存储在变量中的内容。请参阅下面代码中的 cmets。
因为我的状态作为空字符串从该组件传递到 ResultList 组件,所以 ResultList 无法正确呈现。
import React, { Component } from 'react';
import axios from 'axios';
import SearchForm from './components/search_form';
import ResultList from './components/results_list';
class App extends Component {
constructor(props) {
super(props);
this.state = { category: '', term: '', results: [] };
this.handleSearch = this.handleSearch.bind(this);
}
handleSearch(category, term) {
//This is not setting the state!!!!!
this.setState({ category, term });
//The first two console.logs successfully log the arguments to this
function
//The last two console.logs log empty strings even after the above
setState call.
console.log("Received from form: " + category);
console.log("Received from form: " + term);
console.log("#################################");
console.log(this.state.category);
console.log(this.state.term);
console.log('http://swapi.co/api/' + category + '/?search=' + term);
axios.get('http://swapi.co/api/' + category + '/?search=' +
term).then((response) => {
let results = response.data.results;
this.setState({ results });
console.log(this.state.results);
}).catch((error) => {
console.log(error);
});
}
render() {
return (
<div className="container panel panel-default">
<SearchForm handleSearch={this.handleSearch}/>
<ResultList results={this.state.results} category=
{this.state.category}/>
</div>
);
}
}
export default App;
【问题讨论】:
-
this.setState是异步的。使用this.setState({...}, () => { /* do stuff here */}) -
做到了。我是 React 新手,所以感谢您指出这一点。
标签: reactjs components state