gpt4 book ai didi

javascript - react js设置状态从父组件到子组件

转载 作者:行者123 更新时间:2023-11-29 16:38:58 25 4
gpt4 key购买 nike

所以我有一个父子组件。

父级将搜索栏中输入的任何内容作为 prop 传递给子级。

然后应该执行 api fetch,我在控制台中看到了 fetch 对象。我在设置父项的子项状态时遇到困难。

如有任何提示,我们将不胜感激,谢谢,祝您编码愉快 :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);

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'));

最佳答案

我认为首先是你的这部分代码是错误的

axios.get(url)
.then(response => {
console.log(response.data.items)
this.setState({
repo : response.data.items
})
})

首先你需要将 prop repo 传递给 child

<Child repo={this.state.repo} search= {this.state.path} />

要从父级设置子级的状态,不需要对父级做任何更改,在其中添加 componentWillReceiveProps 方法并在那里设置状态

componentWillReceiveProps(nextProps) {
this.setState({
repo: nextProps.repo
})

}

关于javascript - react js设置状态从父组件到子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48389653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com