[英]React use state in different components
我正在创建天气应用程序。 我有一个“搜索”组件(我的表单,axios),在这个组件中,我将我的数据存储在 state 中。 当我提交此表单时,我想用下一个组件加载另一个页面.. 我的问题是如何在其他组件中使用“搜索组件”中的数据,这些数据将在表单提交时加载所以基本上我想提交我的表单然后用天气组件重新加载另一个页面,然后我想将我的数据从搜索移动到天气组件。 在 Weather 组件中,将设置我的背景和其他数据
mport React, { Component } from 'react'; import axios from 'axios'; const KEY = 'fdc0a9d5321ee73e70535ed7d7e052ce' class Search extends Component { state = { value: null, city: null, temp: null } onChange = (e) => { this.setState({ value: e.target.value }) } onSubmit = e => { e.preventDefault() axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${this.state.value}&appid=${KEY}&units=metric`).then(res => { this.setState({ city: this.state.value, temp: res.data.main.temp }) console.log(this.state) }) } render() { return ( <div className="Search"> <form onSubmit={this.onSubmit}> <input onChange={this.onChange}></input> <button>Submit</button> </form> </div> ) } } export default Search import React from 'react'; const Weather = () => { return ( <div> <h1>Lorem</h1> </div> ) } export default Weather
您可以尝试切换组件来实现这一点。 尝试这样的事情
import React, { Component } from 'react';
import axios from 'axios';
const KEY = 'fdc0a9d5321ee73e70535ed7d7e052ce'
class Search extends Component {
state = {
value: null,
city: null,
temp: null
}
onChange = (e) => {
this.setState({
value: e.target.value
})
}
onSubmit = e => {
e.preventDefault()
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${this.state.value}&appid=${KEY}&units=metric`)
.then(res => {
this.setState({
city: this.state.value,
temp: res.data.main.temp
})
const data={
city: this.state.value,
temp: res.data.main.temp
}
this.props.callback(data)
console.log(this.state)
})
}
render() {
return (
<div className="Search">
<form onSubmit={this.onSubmit}>
<input onChange={this.onChange}></input>
<button>Submit</button>
</form>
</div>
)
}
}
export default Search
import React from 'react';
import Search from './Search'
const Weather = () => {
const[formSubmitted,setFormSubmitted]=useState('false)
const callBackHandler=(data)=>{
setFormSubmitted(true)
//do something with the data
}
return (
<div>
{formSubmitted? <h1>Lorem</h1>:<Search callback={(data)=>callBackHandler(data)}/>}
</div>
)
}
export default Weather
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.