2017-05-23 37 views
1

在我的项目中,我在我的子项SearchBar组件中填写了一个输入。将状态从子项传递给父项导致反应组件生命周期重新启动

提交表单时,我想更改我的父组件中searchQuery属性的状态,并将该状态用于api调用。

我将父级(App)组件的handleSubmit函数传递给子级(SearchBar)组件,并将输入值传递给该函数。然后在App组件的handleSubmit函数中,我可以将状态更改为我想要的值。

我的期望是,因为我使用了setState,这将导致渲染函数再次运行,接着是componentDidMount。

然而,整个阵营组件活动周期重新启动,以便this.state.searchQuery总是复位到一个空字符串的它的初始值,因此,我总是寻找一个空字符串。

为什么React组件生命周期的所有功能都重新开始?我怎样才能解决这个问题,所以我能够传递适当的值给componentDidMount中的api调用?

我的代码如下:

父组件(应用程序)

import React, { Component } from 'react'; 
import SearchBar from "./SearchBar.js" 

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     people: [], 
     planets: [], 
     searchQuery: '' 
    } 
    this.handleSubmit = this.handleSubmit.bind(this); 
    console.log('in constructor. this.state.searchQuery is: ', this.state.searchQuery) //empty string 
    } 

    handleSubmit(event, value) { 
    console.log('handle submit is called. value is: ', value); 
    this.setState({ 
     searchQuery: value 
    },()=> { 
     console.log('this.state.searchQuery is:', this.state.searchQuery); //the value I type in 
    }) 
    } 

    componentDidMount() { 
    console.log('this.state.searchQuery is: ', this.state.searchQuery) //empty string 
    //make api call 
    api.fetchPeople(this.state.searchQuery).then((results)=> { 
    //do stuff 
    } 
    } 

    render() { 
    console.log('in render. this.state.searchQuery is: ', this.state.searchQuery) //empty string 
    return (
     <div className='content'> 
     <div className='logo'> 
     </div> 
     <SearchBar submit={this.handleSubmit} /> 
     </div> 
    ); 
    } 
} 

export default App; 

辅元件(搜索栏)

import React, { Component } from 'react'; 
import './SearchBar.css'; 

class SearchBar extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     value: '' 
    } 
    this.handleChange = this.handleChange.bind(this); 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 

    handleChange(event) { 
    this.setState({ 
     value: event.target.value 
    }) 
    } 

    handleSubmit(event) { 
    this.props.submit(event, this.state.value); 
    } 

    render() { 
    return (
     <form onSubmit={this.handleSubmit} className='search-bar'> 
     <input onChange={this.handleChange} value={this.state.value} placeholder='Search Your Destiny' /> 
     </form> 
    ); 
    } 
} 

export default SearchBar; 

回答

1

我的期望是,由于我用这个的setState会导致渲染函数再次运行,接着是componentDidMount。

父级(App)中的handleSubmit函数设置组件的状态,然后触发componentWillUpdate生命周期函数而不是componentDidMount函数。

componentDidMount触发只有当组件安装一次: https://facebook.github.io/react/docs/react-component.html#componentdidmount

+0

我可以看到我的componentDidUpdate状态变化。但是之后整个组件生命周期会再次重新启动。我怀疑它是因为按下Enter会导致我需要防止的页面刷新。我试着在componentDidUpdate中放入event.preventDefault(),但是我不能在那里传递事件,我不确定这是否是正确的想法。 – MattGoldwater

+1

你应该在SearchBar组件的handleSubmit中使用event.preventDefault()。这将阻止页面重新加载。 –

相关问题