首页 > 解决方案 > 如何在返回中显示从其他函数返回的 JSX?

问题描述

我正在尝试使用 openweathermap api 构建一个天气应用程序。正如您在下面的代码中看到的那样,我使用布尔状态来检查表单何时被登顶,以便我可以将该值传递给<Result>组件(我使用硬代码进行了检查并且它可以工作)。我希望函数changeCity(在应用程序中)返回<Result>具有传递城市值的组件,同时更改cityEmpty状态。但是当我在 return() 中传递它时,我遇到了问题{(cityEmpty) ? changeCity() : null}

import React, {useState} from 'react';
import Result from "./components/Result";
import Search from "./components/Search";
import './App.css';

function App() {
    
  const [city, setCity] = useState ("");
  const [cityEmpty, setCityEmpty] = useState(false);
  
  const changeCity = () => {
    setCityEmpty(false);
    return (<Result city={city}/>);
  }

  return (
    <div className="App">
      <Search city={city} setCity={setCity} cityEmpty={cityEmpty} setCityEmpty={setCityEmpty} 
      />
      {(cityEmpty) ? changeCity() : null}
      
    </div>
  );
}

export default App;
import React from "react"

function Search({city, setCity, cityEmpty, setCityEmpty}){

  const handleInputChange = (e) => {
    setCity(e.target.value);
  }

  const handleSumbit = (e) => {
    e.preventDefault();
    console.log(cityEmpty);
    setCityEmpty(true);
    console.log(cityEmpty);
    setCity("");
  }

  return(
  <div>
    <form onSubmit={handleSumbit}>
      <input
      type="text"
      placeholder="Insert city"
      value={city}
      onChange = {handleInputChange}
      >
      </input>
    </form>
  </div>
);

}

export default Search

标签: javascriptreactjs

解决方案


不确定您看到的问题是什么,但我注意到您正在渲染函数内部设置状态,这是一种不好的模式。任何状态更改都会触发组件的重新渲染,如果您在渲染函数中设置状态,那么您将有一个无限循环的重新渲染(但是。

尝试删除setCityEmpty(false).changeCity

const changeCity = () => {
  return (<Result city={city}/>);
}

那么你将如何更新 cityEmpty?目前尚不清楚这里的最终目标是什么。通过更多信息,我们可以找到更好的实现。


推荐阅读