Reactjs 未处理的拒绝(TypeError):无法设置属性';innerText';React钩子中null的定义
我想做一个天气应用程序。但是字符串没有出现在我想要的组件上 如何在React中使用innerText 这是我的Weather.jsxReactjs 未处理的拒绝(TypeError):无法设置属性';innerText';React钩子中null的定义,reactjs,react-hooks,getelementbyid,weather,innertext,Reactjs,React Hooks,Getelementbyid,Weather,Innertext,我想做一个天气应用程序。但是字符串没有出现在我想要的组件上 如何在React中使用innerText 这是我的Weather.jsx import React from "react"; const Weather = () => { const API_KEY = '123456789'; const COORDS = "coords"; const weather = document.getElementById("we
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;
从“React”导入React;
从“样式化组件”导入样式化;
从“../../Components/Weather”导入天气;
const DetailPresenter=()=>{
返回(
{Weather()}
);
};
导出默认的DetailPresenter;
这不是react呈现UI的方式。我们不直接调用函数,而是将它们呈现到JSX“模板”中,以便在必要时进行响应调用。没有任何东西调用您的getWeather
函数来实际获取天气数据。此外,直接DOM操作在react中是一种反模式的操作
Weather
组件当前返回undefined,这对React无效,组件必须返回有效的JSXconst 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
};
const Weather=()=>{
常量API_键='123456789';
const COORDS=“COORDS”;
const[weather,setWeather]=React.useState(“”);
const getWeather=(纬度、液化天然气)=>{
取回(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
)
.然后(功能(响应){
返回response.json();
})
.then(函数(json){
常数温度=json.main.temp;
const place=json.name;
setWeather(`${temperature}℃,\n${place}`);
});
};
React.useffect(()=>{
getWeather(……纬度和经度);
},[]);//如果必须引用元素,可以查看,否则我会使用@Drew Reese提供的解决方案
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>
);
};