我的问题在于我有一些来自SearchForm组件的值。它们将正确的值作为参数传递给handleSearch函数,但是我对setState的调用不起作用。我已经包含console.logs来显示变量中存储的内容。请参阅下面的代码中的评论。反应:子组件正在将它的状态传递给父项,但一旦父项拥有它,父项不会更新其状态
因为我的状态是从该组件传递给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({...},()=> {/ *做这里的东西* /})' –
这样做。我是React新手,非常感谢您指出这一点。 –
[为什么调用setState方法不会立即改变状态?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately) –