gpt4 book ai didi

javascript - react : How to get API data from one component and pass it to another

转载 作者:行者123 更新时间:2023-12-01 02:23:54 25 4
gpt4 key购买 nike

我正在尝试从搜索栏组件传递数据,该组件从 API 调用返回 JSON 到另一个将显示信息的组件。我很难弄清楚。我尝试制作一个容器来容纳这两个组件并传递数据。任何帮助将不胜感激。

谢谢!

我的搜索栏组件

class SearchBar extends Component {
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e){
e.preventDefault();
let reqBody = {
name: this.refs.name.value
};
fetch("/api", {
method: "POST",
body: JSON.stringify(reqBody),
headers: {"Content-Type": "application/json"}
})
.then((res) => {
if (res.ok){
return res.json();
} else {
throw new Error ('Something went wrong');
}
}).then((json) => {
console.log(json)
this.props.onDataFetched(json)
})
}


render() {
return (
<div >
<form onSubmit={this.handleSubmit}>
<input placeholder = "Enter Name" type="text" ref = "name"/>
<button type ="Submit"> Search</button>

</form>
</div>
);
}
}

显示的组件

class History extends Component {
render() {
return (
<div >
<h2> History</h2>


<ul>
<li>
//display data here

</li>


</ul>



</div>
);
}
}

我的容器组件

class Container extends Component {
constructor(props){
super(props);
this.state ={
history : []
}
this.handleResultChange = this.handleResultChange.bind(this)
}
handleResultChange(history){
this.setState({
history,
})
}

render() {
return (
<div >
<SearchBar onDataFetched={this.handleResultChange}/>
<History data={this.state.history}/>
</div>
);
}
}

最佳答案

您可以在搜索组件本身中处理表单提交。将搜索值(输入值)传递给容器组件。

class SearchBar extends React.Component {
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(e){
e.preventDefault();
let reqBody = {
name: this.refs.name.value
};

console.log(reqBody);
this.props.onDataFetched(reqBody);
}


render() {
return (
<div >
<form onSubmit={this.handleSubmit}>
<input placeholder = "Enter Name" type="text" ref = "name"/>
<button type ="Submit"> Search</button>

</form>
</div>
);
}
}

class Container extends React.Component {
constructor(props){
super(props);
this.state ={
history : []
}
this.handleChange = this.handleChange.bind(this)
}

handleChange(searchValue){
console.log(searchValue);
}

render() {
return (
<div >
<SearchBar onDataFetched={this.handleChange} />
</div>
);
}
}
ReactDOM.render(<Container />, mountNode )

现在说,执行此操作的理想方法是如上所述使用 redux 和 redux 表单。

https://redux.js.org/

https://redux-form.com/

这将帮助您在将来节省大量时间,因为您将拥有正确的结构来执行此操作。

关于javascript - react : How to get API data from one component and pass it to another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48970125/

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