Кнопка «Назад» не отображает информацию — реагирует маршрутизатор dom v5.2

#javascript #reactjs #react-router

Вопрос:

Когда я нажимаю кнопку «Назад», которая использует историю использования в react-router-dom v5.2, моя страница «прогнозы/:zip» возвращается на правильный почтовый индекс, но не показывает правильную информацию о прогнозе.

Итак, если я найду прогнозы/90210 и прогнозы/12345 и вернусь назад, URL-адрес моего браузера покажет прогнозы/90210, но покажет прогноз для прогноза/12345.

Я не вижу ни реквизита, ни какой-либо информации, когда наношу ответный удар. Я могу обернуть прогнозы с помощью withRouter, но он просто отображает путь без информации о состоянии в моих реквизитах.

Кнопка «Назад» расположена в Forecasts.js в разделе «Постоянный элемент».

Может кто-нибудь, пожалуйста, дать мне знать, что я могу попробовать? Спасибо.

App.js

 function App() {

  const [zipCode, setZipCode] = React.useState("");

  const handleChange = (newzipCode) => {
    setZipCode(newzipCode);
    console.log(newzipCode)
  };

  return (
    <BrowserRouter>
      <div className="container mt-2" style={{ marginTop: 40 }}>
        <Switch>
          <Route exact path="/">
            <Redirect to="/home" />
          </Route>
          <Route path="/home">
            <Home changeZip={handleChange} />
          </Route>
          <Route path={`/forecasts/:zip`}>
            <Forecasts zip={zipCode} />
          </Route>
        </Switch>
      </div>
    </BrowserRouter>
  );
}

export default App;
 

Home.js

 const Home = (props) => {
  const [searchText, setSearchText] = useState(
    props.zip ? props.zip : "45678"
  );
  // const [newZip, setnewZip] = useState("");

  const handleInputChange = (event) => {
    const enteredText = event.target.value;
    setSearchText(enteredText);
  };

  const useStyles = makeStyles({
    parent: {
      // borderColor: "red",
      // borderStyle: "solid",
      height: "100%",
      width: "100%",
      justifyContent: "center",
      // display: 'inline-block',
      // textAlign: "center",
      // alignItems: "center",
    },
    child: {
      // borderColor: "blue",
      // borderStyle: "solid",
      justifyContent: "center",
      textAlign: "center",
      display: "inline-block",
      alignItems: "center",
    },
  });

  const classes = useStyles();

  const passZip = () => {
    // setnewZip(searchText);
    props.changeZip(searchText);
    console.log(props.changeZip);
  };

  return (
    <>
      <Grid className={classes.parent} container>
        <Grid className={classes.child} item xs={12} sm={4}>
          <span className="search-form">
            <div className="search-form__input">
              <TextField
                id="standard-basic"
                label="Zip"
                onChange={handleInputChange}
                value={searchText}
              />
            </div>
            <div className="search-form__submit">
              <Button
                component={Link}
                to={`/forecasts/${searchText}`}
                onClick={passZip}
              >
                Search
              </Button>
            </div>
          </span>
        </Grid>
      </Grid>
    </>
  );
};

export default Home;
 

Forecasts.js

 const Forecasts = (props) => {

    let history = useHistory();

  const Item = () => {
    console.log(history)
    return (
      <>
        <button onClick={() => history.goBack()}>Back</button>
      </>
    );
  };

  const [forecasts, setForecasts] = useState([]);

  const searchLocationChange = (zip) => {
    console.log(zip);

    const weatherURL = `http://localhost:3001/${zip}`;

    console.log(weatherURL);

    fetch(weatherURL)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        // const dailyData = data.list.filter(reading => reading.dt_txt.includes("18:00:00"))
        // setForecasts(data.list);
        setForecasts(data);
      });

    console.log(props);
  };

  const useStyles = makeStyles({
    parent: {
      // borderColor: "blue",
      // borderStyle: "solid",
      height: "100%",
      justifyContent: "center",
    },
    child: {
      borderColor: "green",
      borderStyle: "solid",
      // justifyContent: "center",
      textAlign: "center",
    },
    listitem: {
      display: "inline-block",
    },
  });

  const classes = useStyles();

  const [zipCode, setZipCode] = React.useState(props.zip ? props.zip : "45678");

  useEffect(() => {
    searchLocationChange(zipCode);
  }, [zipCode]);

  const handleChange = (newzipCode) => {
    setZipCode(newzipCode);
    console.log(newzipCode);
  };

  return (
    <Grid className={classes.parent} container>
      {Item()}
      <Home changeZip={handleChange} zip={zipCode}/>
      {forecasts amp;amp;
        forecasts.slice(0, 5).map((forecast, index) => {
          return (
            <DayCard
              key={index}
              temp={forecast.main.temp}
              desc={forecast.weather[0].description}
              dt={forecast.dt}
            />
          );
        })}
    </Grid>
  );
};