1

我正在构建一个天气应用程序,我需要将天气卡分离到它自己的组件中。到目前为止,虽然我的Weather.js文件中有天气卡,但它一直运行良好。但是现在我已将天气卡分离到它自己的组件中,但我无法访问状态。

这是我拥有状态的主要组件:

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}/>
    )
  }
}

这是我尝试使用状态的另一个组件

const WeatherCard = (props) => {
  return (
    <div>
      <h2>Today</h2>
      <span>{this.props.items.location.country}</span>
    </div>
  )
}

我得到的错误是: undefined has no properties

4

2 回答 2

1
    render() {
    const { error, isLoaded, items } = this.state;
    return (
      <WeatherCard items={items}/>
    )
  }

在你的天气组件中

 const WeatherCard = (props) => {
  return (
    <div>
      <h2>Today</h2>
      <span>{props.items.location.country}</span>
    </div>
  )
于 2020-07-10T10:27:18.990 回答
0
  render() {
    const { error, isLoaded, items } = this.state;
    return (
      <WeatherCard items={this.state}/>
    )
  }

改成

  render() {
    const { error, isLoaded, items } = this.state;
    return (
      <WeatherCard items={items}/>
    )
  }

const WeatherCard = (props) => {
  return (
    <div>
      <h2>Today</h2>
      <span>{this.props.items.location.country}</span>
    </div>
  )
}

改成这个

  const WeatherCard = (props) => {
          return (
            <div>
              <h2>Today</h2>
              <span>{props.items.location.country}</span>
            </div>
          )
        }
于 2020-07-10T10:38:20.457 回答