更改redux存储后,可以如何重新渲染组件?

时间:2020-09-12 18:23:26

标签: javascript reactjs redux jsx

当前有两个组件的问题,即Body.js和NavBar.js。我在主体组件中运行了useEffect,该组件捕获用户的地理位置并获取其城市的天气信息。我的问题是,当用户在NavBar.js中搜索城市时,我将城市天气信息设置为redux商店,然后我希望它重新呈现Body.js组件,但带有搜索到的城市信息,我似乎无法弄清楚如何使它工作。这是我的身体成分

function Body(props) {
  const [location, setLocation] = useState({});
  const [info, setInfo] = useState({});

  function getGeo() {
    navigator.geolocation.getCurrentPosition(function (position) {
      setLocation({
        lat: position.coords.latitude,
        long: position.coords.longitude,
      });
    });
  }

  useEffect(() => {
    getGeo();

    if (location.lat === undefined || location.long === undefined) {
      return;
    }

    fetch(
      `http://api.openweathermap.org/data/2.5/weather?lat=${location.lat}&lon=${location.long}&units=metric&appid=4key`
    )
      .then((response) => {
        return response.json();
      })
      .then((result) => {
        if (props.searchedCity === null) {
          setInfo(result);
        } else {
          setInfo(props.searchedCity);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }, [location.lat, location.long, setInfo]);

//small part of return statement theres a lot more using the info state

return (
    <>
      <img className="adv" src="image1.png" />
      <div className="grid-block-container">
        <div className="city-weather">
          <div className="info-container">
            <h2>{info.name || "Loading..."} Weather</h2>
            <p>as of 12:00 pm CDT</p>
            <h1>
              {parseInt((info.main?.temp * 9) / 5 + 32) || "Loading..."}&#176;
            </h1>
)

}
const mapStateToProps = (state) => {
  return {
    searchedCity: state.searchedCity,
  };
};

export default connect(mapStateToProps, null)(Body);

NavBar.js只是根据用户输入获取新的天气信息,并将其设置为redux存储“ searchedCity”,最初将其设置为null(此功能已被检查)。虽然这会更新redux存储,但显然不会引起Body。 js重新呈现,并且信息未被使用。更改redux后,如何重新渲染body.js并将信息设置为redux存储中的内容?感谢您提供的帮助,我知道这是个大问题。

0 个答案:

没有答案