【发布时间】:2017-10-24 00:34:30
【问题描述】:
在我的项目中,我正在我的子 SearchBar 组件中填写一个输入。
提交表单后,我想更改父组件中 searchQuery 属性的状态,并将该状态用于 api 调用。
我将一个handleSubmit 函数从父(App) 组件传递给子(SearchBar) 组件,并将输入值传递给该函数。然后在 App 组件上的 handleSubmit 函数中,我可以将状态更改为我想要的值。
我的预期是,由于我使用了 setState,这将导致渲染函数再次运行,然后是 componentDidMount。
但是,整个 React 组件生命周期已经重新启动,所以 this.state.searchQuery 总是重置为空字符串的初始值,因此我总是搜索空字符串。
为什么 React 组件生命周期的所有功能都重新开始?我该如何解决这个问题,以便能够将正确的值传递给 componentDidMount 中的 api 调用?
我的代码如下:
父组件(App)
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;
【问题讨论】:
标签: reactjs