反应js设置状态从父组件到子组件 [英] react js set state from parent to child component
问题描述
所以我有一个父级和子级组件.
So I have a parent and children component.
父母将在搜索栏中键入的内容作为对孩子的支持.
Parent passes whatever is typed in the search bar as a prop to the children.
然后应该执行api提取,我在控制台中看到了fetch对象.我在设置父母的孩子状态时遇到困难.
then the api fetch should be executed, I see the fetch object in the console. I'm having difficulties setting the children state from the parent.
任何提示将不胜感激,谢谢您,并期待编码:D
Any tips would be appreciated, thank you and happing coding :D
class HelloComponent extends React.Component {
render () {
return <h1>Github API repositories </h1>;
}
}
class Parent extends React.Component {
constructor (props) {
super (props);
this.boo = this.boo.bind(this);
this.state = {path: ''};
}
boo = (event) => {
event.preventDefault();
//alert('it works!');
let url = 'https://api.github.com/search/repositories?q='+ this.state.path;
//let parameter = this.state.path;
console.log(url);
我尝试使用this.props或仅使用this.response..etc
I tried using this.props or just this.response..etc
axios.get(url)
.then(response => {
console.log(response.data.items)
this.setState({
repo : this.props.response.data.items
})
})
}
//set the state from the search bar
searchQuery = (event) => {
this.setState({ path : event.target.value });
}
render() {
return(
//call Repositories component and pass the current state as props
<div>
<form onSubmit={this.boo}>
<input type="text" onChange={this.searchQuery} />
<input type="submit" value="Search"/>
</form>
<Child search= {this.state.path} />
{/* <button onClick={this.boo}>fuck</button> */}
</div>
);
}
}
class Child extends React.Component {
constructor (props) {
super (props);
//this.boo = this.boo.bind(this);
this.state = { repo : ''};
}
render () {
{/*
const titles = this.state.repo.map( (repo) =>
<tr key={ repo.id }>
<td> { repo.name }</td>
<td><a href={repo.html_url}>{repo.html_url}</a></td>
</tr>
);
return (
<div>
<table>
<tbody>
<tr><th>Name</th><th>URL</th></tr>
{titles}
</tbody>
</table>
</div>
);
*/}
return (
<h1>{this.state.repo}</h1>
);
}
}
class App extends React.Component {
render () {
return (
<div>
<HelloComponent />
<Parent />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
推荐答案
我首先认为您的代码的这一部分是错误的
I think first is this part of your code is wrong
axios.get(url)
.then(response => {
console.log(response.data.items)
this.setState({
repo : response.data.items
})
})
首先,您需要将道具回购传递给孩子
First you need to pass prop repo to child
<Child repo={this.state.repo} search= {this.state.path} />
要从父级设置子级状态,无需在父级中进行任何更改,只需在其中添加componentWillReceiveProps方法并在其中设置setState
To set state of child from parent, you don't need to make any change in parent, Add componentWillReceiveProps method in and setState there
componentWillReceiveProps(nextProps) {
this.setState({
repo: nextProps.repo
})
}
这篇关于反应js设置状态从父组件到子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!