2017-08-18 69 views
0

我的问题在于我有一些来自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; 
+1

'this.setState'是异步的。使用'this.setState({...},()=> {/ *做这里的东西* /})' –

+0

这样做。我是React新手,非常感谢您指出这一点。 –

+0

[为什么调用setState方法不会立即改变状态?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately) –

回答

2

我将阐述我在我的评论说:性能

Component#setState推迟和批次状态更新请求。因此,您不能在Component.state上通过呼叫后立即使用新值更新中继。

setState提供了第二个参数 - 执行状态更新操作后调用的回调函数。在你的情况下,它看起来像

this.setState({ category, term },() => { 
    console.log(this.state.term, this.state.category) 
    // now you can use them 
}) 
+1

接受答案。谢谢你的帮助。 –

+0

我不认为即使这个工程。 回调函数将具有相同的状态,而不是更新的状态。 如果你想在回调中使用新的变量,你将不得不明确地将它们传递给函数 –

+0

@bhaskarsharma我不知道我遵循 - 你是什么意思“如果你想在回调中使用新的变量? “ –

0

setState不是一个同步函数调用,所以调用setstate函数可能不会立即更新状态。从文档

的setState()入列更改组件状态并告诉阵营,这个组件和它的孩子们需要被重新渲染与 更新的状态。这是用于响应事件处理程序和服务器响应更新用户界面的主要方法。可以考虑使用 setState()作为请求,而不是立即更新 组件的命令。为了获得更好的感知性能,React可能会延迟它,然后通过一次更新几个组件。反应不 保证状态的变化会立即

施加,从而console.log(this.state.category); console.log(this.state.term); 将不记录更新的状态。但是如果您将这些语句放在渲染函数中,您将看到在下一个渲染中设置的正确状态。

了解更多关于https://facebook.github.io/react/docs/react-component.html#setstate

相关问题