[英]Pass state from one component to another in ReactJs
I am building a Weather Application, and I need to seperate the Weather card into its own component.我正在构建一个天气应用程序,我需要将天气卡分离到它自己的组件中。 So far, while I had the Weather card in my
Weather.js
file it has been working good.到目前为止,虽然我的
Weather.js
文件中有 Weather 卡,但它一直运行良好。 But now I have seperated the Weather card into its own component but I cannot access the state.但是现在我已经将天气卡分离到它自己的组件中,但我无法访问 state。
This is my main component where I have my state:这是我的主要组件,我有我的 state:
export default class Weather extends React.Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, items: [], selectedValue: '' }; } componentDidMount() { fetch("http://api.weatherapi.com/v1/forecast.json?key=ca021cd2c43544e0be7112719202206&q=kosovo&days=3").then(res => res.json()).then( (result) => { this.setState({ isLoaded: true, items: result }); }, (error) => { this.setState({ isLoaded: true, error }); } ); } render() { const { error, isLoaded, items } = this.state; return ( <WeatherCard items={this.state}/> ) } }
This is the other component that I am trying to use the state这是我尝试使用 state 的另一个组件
const WeatherCard = (props) => { return ( <div> <h2>Today</h2> <span>{this.props.items.location.country}</span> </div> ) }
The error that I get is: undefined has no properties我得到的错误是: undefined has no properties
render() {
const { error, isLoaded, items } = this.state;
return (
<WeatherCard items={items}/>
)
}
And in your weather component在你的天气组件中
const WeatherCard = (props) => {
return (
<div>
<h2>Today</h2>
<span>{props.items.location.country}</span>
</div>
)
render() {
const { error, isLoaded, items } = this.state;
return (
<WeatherCard items={this.state}/>
)
}
change to改成
render() {
const { error, isLoaded, items } = this.state;
return (
<WeatherCard items={items}/>
)
}
and和
const WeatherCard = (props) => {
return (
<div>
<h2>Today</h2>
<span>{this.props.items.location.country}</span>
</div>
)
}
change to this改成这个
const WeatherCard = (props) => {
return (
<div>
<h2>Today</h2>
<span>{props.items.location.country}</span>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.