reactjs - 如何将反应路由器中的状态传递给组件
问题描述
我试图制作一个单独的页面/组件进行搜索,我想知道如何将状态传递给不同的组件?我想将渲染/返回部分中的所有内容复制并粘贴到不同的组件中,然后使用反应路由器访问该页面,我该怎么做?任何帮助是极大的赞赏!
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Weather from "./Weather.js";
import Skycons from "react-skycons"
import { geticon } from "./geticon.js"
import ToggleDisplay from 'react-toggle-display';
import Form from "./Form.js";
import Layout from "./layout.js";
import Hike from "./Hike.js";
import 'bootstrap/dist/css/bootstrap.min.css';
import {FormControl, FormGroup, ControlLabel, HelpBlock, Checkbox, Radio, Button} from 'react-bootstrap';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const API_KEY = "2a41aeea56aabfb9ff1218730fc32426";
class App extends React.Component {
state = {
temperature: "",
city: "",
city2:"",
country: "",
msg: "",
pressure: "",
humidity: "",
description: "",
rain:"",
main:"Drizzle",
icon: "09d",
error: "",
date: "",
month:"",
lat:"",
show: false,
lng:"",
year:"",
clouds:""
}
handlenum1Change (evt) {
let temp = (evt.target.value);
}
getDate() {
var date = new Date().getDate();
var month = new Date().getMonth() + 1;
var year = new Date().getFullYear();
this.setState({ date,year,month});
}
componentDidMount() {
this.getDate();
}
getWeather = async (e) => {
e.preventDefault();
this.setState({ showResults: true });
const city = e.target.city.value;
const api_call = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
https://www.hikingproject.com/data/get-trails-by-id?ids=7000108,7002175,7005207,7001726,7005428&key=YOU
const data = await api_call.json();
if (city) {
this.setState({
temperature: data.main.temp,
city: data.name,
clouds:data.clouds.all,
main: data.weather[0].main,
icon: data.weather[0].icon,
rain: data.rain,
pressure: data.main.pressure,
humidity: data.main.humidity,
description: data.weather[0].description,
error: ""
});
} else {
this.setState({
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
pressure:undefined,
rain : undefined,
error: "Please enter the values."
});
}
var clouds= data.clouds.all;
if (clouds>30){
this.setState({
msg:" Poor conditions for stargazing!! "
})
}
else{
this.setState({
msg: " Good conditions for stargazing! no rain in forecast! "
})
}
}
getTrail = async (e) => {
e.preventDefault();
const city = e.target.city2.value;
this.setState({
show: !this.state.show
});
const country = e.target.country.value;
const api_call = await fetch(`https://api.wunderground.com/api/b1049a092a7f69ea/astronomy/q/${country}/${city}.json`);
const data = await api_call.json();
if (city) {
this.setState({
moon_phase: data.moon_phase.ageOfMoon,
moon_hour: data.moon_phase.hemisphere,
moon_rise: data.moon_phase.moonrise.hour,
moon_rises: data.moon_phase.moonrise.minute,
moon_state: data.moon_phase.phaseofMoon,
moon_set: data.moon_phase.moonset.hour,
moon_sets: data.moon_phase.moonset.minute,
sunset: data.sun_phase.sunset.hour,
sunsets: data.sun_phase.sunset.minute,
sunrise:data.sun_phase.sunrise.hour,
sunrises:data.sun_phase.sunrise.minute
});
} else {
this.setState({
moon_phase: undefined,
sunset: undefined
});
}
}
// const BasicExample = () => (
// <Router>
// <div>
// <ul className="navbar-nav ml-auto">
// <li className="nav-item">
// <Link to="/about">About</Link>
// </li>
// <li className="nav-item">
// <Link to="/topics">Topics</Link>
// </li>
// </ul>
// <hr />
// <Route path="/about" component={About} />
// <Route path="/topics" component={Topics} />
// </div>
// </Router>
// );
render() {
return (
<div>
<div>
<br></br><br></br><br></br><br></br><br></br><br></br>
<div className="container">
<div className="row">
<div id="city">
<div className="form-group mb-2">
<div className="form-group mx-sm-3 mb-2">
<form className="form-inline" onSubmit={this.getWeather} >
<input type="text" name="city" className="form-control" onChange={this.handlenum1Change} placeholder="Input City..."/>
<button className="btn btn-primary">Get Weather</button>
</form>
<Weather className="fish"
city={this.state.city}
temperature={this.state.temperature}
humidity={this.state.humidity}
clouds={this.state.clouds}
pressure={this.state.pressure}
description={this.state.description}
rain={this.state.rain}
icon={this.state.icon}
error={this.state.error}
/>
<h3> {this.state.msg} </h3>
<div className="clearfix">
<div className="date"><p id="d"> {this.state.date}/{this.state.month}/{this.state.year}</p>
<div>
<Form getTrail={this.getTrail} />
{this.state.moon_phase && <div> moon_phase: {this.state.moon_phase}</div> }
{this.state.sunset && this.state.sunsets && <div className="row"> <p> sunset Time: {this.state.sunset} </p> : <p> {this.state.sunsets} </p> </div> }
{this.state.sunrise && this.state.sunrises && <div className="row"> <p> sunrise Time: {this.state.sunrise} </p> : <p> {this.state.sunrises} </p></div> }
{this.state.moon_set && this.state.moon_sets && <div className="row"> <p> moonset: {this.state.moon_set} </p> : <p> {this.state.moon_sets} AM</p> </div> }
<div class="w-100"> </div>
{this.state.moon_rise && this.state.moon_rises && <div className="row"> <p>moonrise - {this.state.moon_rise} </p> : <p> {this.state.moon_rises} PM</p> </div> }
{this.state.moon_state && <p> {this.state.moon_state} moon </p> }
{this.state.moon_hour && <p> hemisphere: {this.state.moon_hour} </p> }
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
};
export default App;
解决方案
如果我对你的理解正确,那么你需要使用render
而不是component
inreact-router
<Route path="/about" render={()=> <About parentState={this.state} />} />
您可以在 About 组件中访问它们,例如
this.props.parentState.main // should render "Drizzle"
推荐阅读
- jupyter-notebook - 我如何平均 20 个保存的 ANN 模型?
- remix - 如何使混音连接到仲裁网络
- javascript - Bot Framework瀑布中的命名函数?
- vue.js - 如何在vuejs中格式化电话(即xxx-xxx-xxxx)
标签 - c# - SQLite 的相对路径不适用于 WIX 工具集
- python - 使用 cx_Freeze for windows 构建的 python tkinter exe 不会显示 GUI
- javascript - Vue Mixin 用于子组件
- python - Django - 十进制类型的对象不是 JSON 可序列化的,并且在视图中转换为模型数据
- amazon-s3 - 在 S3 中保存文件和在 Cloudfront 上使其无效之间的时间。我应该等多久?
- java - Spring Web 应用程序和使用线程池的异步执行