簡體   English   中英

React 在不同組件中使用 state

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM