javascript - 如何在返回中显示从其他函数返回的 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
解决方案
不确定您看到的问题是什么,但我注意到您正在渲染函数内部设置状态,这是一种不好的模式。任何状态更改都会触发组件的重新渲染,如果您在渲染函数中设置状态,那么您将有一个无限循环的重新渲染(但是。
尝试删除setCityEmpty(false)
.changeCity
const changeCity = () => {
return (<Result city={city}/>);
}
那么你将如何更新 cityEmpty?目前尚不清楚这里的最终目标是什么。通过更多信息,我们可以找到更好的实现。
推荐阅读
- opencv - 掠角下的 OpenCV 棋盘识别
- primefaces - 验证表单值后如何设置 p:commandLink 标签“目标”值?
- javascript - 当我在同一行复选框上打勾时,如何在另一个表中获取表行数据?
- sql-server - 临时表 - 是否有内置方法来确定在一系列日期内已更改的行
- javascript - Node.js/JavaScript/SQL - 序列的顺序
- python - SQL Alchemy:理解 expire_on_commit
- gwt - 如何根据 GWT 中另一个中的选择填充一个下拉列表?
- junit - 如何在测试用例 HTTP 方法 URL 中访问变量值
- postgresql - 如何将“YYYY-DD-MM HH:MI:SS.MS +00:00”形式的字符串转换为postgres timestamptz,其中最后四个字符是时区偏移量?
- scala - 使用 scala spark 将固定宽度的文件插入 Hive