【问题标题】:Unhandled Rejection (TypeError): Cannot set property 'innerText' of null in React-hooks未处理的拒绝(TypeError):无法在 React-hooks 中设置 null 的属性“innerText”
【发布时间】:2021-03-26 20:51:19
【问题描述】:

我想做一个天气应用。但是字符串没有出现在我想要的组件上。

innerText 在 React 中如何使用?

这是我的 Weather.jsx

import React from "react";

const Weather = () => {
  const API_KEY = '123456789';
  const COORDS = "coords";
  const weather = document.getElementById("weather");

  const getWeather = (lat, lng) => {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
    )
      .then(function (response) {
        return response.json();
      })
      .then(function (json) {
        const temperature = json.main.temp;
        const place = json.name;
        weather.innerText = `${temperature}℃,\n ${place}`;
      });
  };
};
export default Weather;

这是显示天气的屏幕代码。

import React from "react";
import styled from "styled-components";
import Weather from "../../Components/Weather";

const DetailPresenter = () => {
  
  return (
    <>
      <DetailContainer>
        <div id="weather">{Weather()}</div>  
      </DetailContainer> 
    </>
  );
};
export default DetailPresenter;

【问题讨论】:

  • 如果一定要引用元素,可以看this post,否则我会选择@Drew Reese提供的解决方案

标签: reactjs react-hooks getelementbyid weather innertext


【解决方案1】:

这不是 react 渲染 UI 的方式。我们不直接调用函数,而是将它们渲染到 JSX“模板”中,以便 React 在必要时调用。 实际上没有调用你的 getWeather 函数来获取天气数据。此外,直接 DOM 操作是 react 中的一种反模式。

  1. 将要显示的文本保存到本地组件状态。
  2. 渲染它。您的 Weather 组件当前返回 undefined,这对 React 无效,组件必须返回有效的 JSX。

天气

const Weather = () => {
  const API_KEY = '123456789';
  const COORDS = "coords";
  const [weather, setWeather] = React.useState('');

  const getWeather = (lat, lng) => {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
    )
      .then(function (response) {
        return response.json();
      })
      .then(function (json) {
        const temperature = json.main.temp;
        const place = json.name;
        setWeather(`${temperature}℃,\n ${place}`);
      });
  };

  React.useEffect(() => {
    getWeather(......lat & long);
  }, []); // <-- run effect once on component mount

  return weather; // <-- string is valid JSX
};

详细介绍

import React from "react";
import styled from "styled-components";
import Weather from "../../Components/Weather";

const DetailPresenter = () => {
  
  return (
    <DetailContainer>
      <Weather /> // <-- render component, don't invoke
    </DetailContainer> 
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2021-05-17
    • 2020-06-22
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多