在反应中更改状态时不会重新渲染组件
Component is not re rendering when state is changed in react
我连续 2 天都遇到这个错误,我无法修复!!!所以,我正在使用 https://www.weatherapi.com/ 这个 api 创建一个天气应用程序,我使用了 bootstrap 的 Navbar 并且有这个搜索选项我可以使用所以如果用户搜索特定状态,它将显示来自该状态的数据,因为我使用不同的组件来保持我的 App.js
干净 我已经在 App.js
中声明了一个状态,我可以通过 Navbar.js
中的按钮更新它将作为道具传递给 Display.js
(显示数据),但是当我进入一个状态并点击提交时,页面会重新加载(我认为)并且它会返回到我用作虚拟对象的原始状态.它不会使用新数据重新呈现 Display.js
。我尝试通过在浏览器上使用它来检查它,它 returns 响应。
这是代码。
App.js
import React,{useState} from 'react';
import Navbar from './Navbar.js';
import Display from './Display.js'
function App() {
const[placeName,setPlaceName] = useState('Raipur')
let key = 'not gonna tell';
return (
<>
<Navbar setPlaceName={setPlaceName} />
<Display key={key} placeName={placeName} />
</>
);
}
export default App;
Navbar.js
import React from 'react';
function Navbar(props) {
return(
<>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container-fluid">
<a className="navbar-brand" href="/">Navbar</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="/navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<a className="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/">Link</a>
</li>
<li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" href="/" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul className="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a className="dropdown-item" href="/">Action</a></li>
<li><a className="dropdown-item" href="/">Another action</a></li>
<li><hr className="dropdown-divider"/></li>
<li><a className="dropdown-item" href="/">Something else here</a></li>
</ul>
</li>
<li className="nav-item">
<a className="nav-link disabled">Disabled</a>
</li>
</ul>
<form className="d-flex">
<input className="form-control me-2" type="search" placeholder="Search" aria-label="Search"/>
<button onClick={props.setPlaceName} className="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</>
);
}
export default Navbar;
Display.js
import React,{useState,useEffect} from 'react';
function Display(props) {
const[weatherInfo,setWeatherInfo] = useState([]);
const getWeatherInfo = async () =>{
let url =`https://api.weatherapi.com/v1/current.json?key=${props.key}&q=${props.placeName}&aqi=no`;
let weatherInfo = await fetch(url);
let parsedweatherInfo = await weatherInfo.json();
setWeatherInfo(parsedweatherInfo.location);
}
// eslint-disable-next-line
useEffect(async () =>{
getWeatherInfo();
},[])
return (
<>
<div className="container">
<div className="row">
{Object.values(weatherInfo).map((key,value)=>{
return(
<div className="col" key={key}>
{key}
</div>
)
})}
</div>
</div>
</>
)
}
export default Display;
响应示例
{
"location": {
"name": "London",
"region": "City of London, Greater London",
"country": "United Kingdom",
"lat": 51.52,
"lon": -0.11,
"tz_id": "Europe/London",
"localtime_epoch": 1631360600,
"localtime": "2021-09-11 12:43"
},
"current": {
"last_updated_epoch": 1631359800,
"last_updated": "2021-09-11 12:30",
"temp_c": 21.0,
"temp_f": 69.8,
"is_day": 1,
"condition": {
"text": "Partly cloudy",
"icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
"code": 1003
},
"wind_mph": 11.9,
"wind_kph": 19.1,
"wind_degree": 250,
"wind_dir": "WSW",
"pressure_mb": 1017.0,
"pressure_in": 30.03,
"precip_mm": 0.0,
"precip_in": 0.0,
"humidity": 64,
"cloud": 50,
"feelslike_c": 21.0,
"feelslike_f": 69.8,
"vis_km": 10.0,
"vis_miles": 6.0,
"uv": 5.0,
"gust_mph": 10.5,
"gust_kph": 16.9
}
}
希望你能帮上忙:)
当用户点击按钮时,您实际上并没有更新状态。
button onClick={props.setPlaceName}
应该是这样的
button onClick={() => props.setPlaceName("Hello world")}
代码的相关部分在 Navbar
组件中:您没有向 setter 函数提供新的 placeName
。
因此,例如,您的 Navbar
组件应该看起来像这样:
function Navbar(props) {
// This state stores the updated input value
const [inputPlaceName, setInputPlaceName] = useState('');
// This function provides `setPlaceName` with the input value
function setGlobalPlaceName() {
props.setPlaceName(inputPlaceName);
}
return (
<form>
<input type="search" onChange={setInputPlaceName} />
<button onClick={setGlobalPlaceName} type="submit">
Search
</button>
</form>
);
}
然后,尝试订阅 Display
组件以更新 props.placeName
。这是通过将其添加到其 useEffect
:
的依赖项数组来完成的
useEffect(getWeatherInfo, [props.placeName])
正在运行的应用程序 https://codesandbox.io/s/jovial-pascal-kww85?file=/src/App.js
注:
- Prop 名称不能作为键,因为这个名称是保留的,用于唯一标识组件。(我使用 apikey 作为名称)
<Display apikey={key} placeName={placeName} />
- 在导航栏中,您必须使用另一种状态来跟踪文本框中的输入。
const [input, setInput] = useState("");
- 在 Navbar 中它应该是 onClick={() => props.setPlaceName(input)}
value={input}
onChange={(e) => setInput(e.target.value)}
- 提交时的表单元素阻止默认不刷新页面。
<form className="d-flex" onSubmit={(e) => e.preventDefault()}>
- 在 props.placename 更改时显示调用 useEffect。
useEffect(async () => {
getWeatherInfo();
}, [props.placeName]);
我连续 2 天都遇到这个错误,我无法修复!!!所以,我正在使用 https://www.weatherapi.com/ 这个 api 创建一个天气应用程序,我使用了 bootstrap 的 Navbar 并且有这个搜索选项我可以使用所以如果用户搜索特定状态,它将显示来自该状态的数据,因为我使用不同的组件来保持我的 App.js
干净 我已经在 App.js
中声明了一个状态,我可以通过 Navbar.js
中的按钮更新它将作为道具传递给 Display.js
(显示数据),但是当我进入一个状态并点击提交时,页面会重新加载(我认为)并且它会返回到我用作虚拟对象的原始状态.它不会使用新数据重新呈现 Display.js
。我尝试通过在浏览器上使用它来检查它,它 returns 响应。
这是代码。
App.js
import React,{useState} from 'react';
import Navbar from './Navbar.js';
import Display from './Display.js'
function App() {
const[placeName,setPlaceName] = useState('Raipur')
let key = 'not gonna tell';
return (
<>
<Navbar setPlaceName={setPlaceName} />
<Display key={key} placeName={placeName} />
</>
);
}
export default App;
Navbar.js
import React from 'react';
function Navbar(props) {
return(
<>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container-fluid">
<a className="navbar-brand" href="/">Navbar</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="/navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<a className="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/">Link</a>
</li>
<li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" href="/" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul className="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a className="dropdown-item" href="/">Action</a></li>
<li><a className="dropdown-item" href="/">Another action</a></li>
<li><hr className="dropdown-divider"/></li>
<li><a className="dropdown-item" href="/">Something else here</a></li>
</ul>
</li>
<li className="nav-item">
<a className="nav-link disabled">Disabled</a>
</li>
</ul>
<form className="d-flex">
<input className="form-control me-2" type="search" placeholder="Search" aria-label="Search"/>
<button onClick={props.setPlaceName} className="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</>
);
}
export default Navbar;
Display.js
import React,{useState,useEffect} from 'react';
function Display(props) {
const[weatherInfo,setWeatherInfo] = useState([]);
const getWeatherInfo = async () =>{
let url =`https://api.weatherapi.com/v1/current.json?key=${props.key}&q=${props.placeName}&aqi=no`;
let weatherInfo = await fetch(url);
let parsedweatherInfo = await weatherInfo.json();
setWeatherInfo(parsedweatherInfo.location);
}
// eslint-disable-next-line
useEffect(async () =>{
getWeatherInfo();
},[])
return (
<>
<div className="container">
<div className="row">
{Object.values(weatherInfo).map((key,value)=>{
return(
<div className="col" key={key}>
{key}
</div>
)
})}
</div>
</div>
</>
)
}
export default Display;
响应示例
{
"location": {
"name": "London",
"region": "City of London, Greater London",
"country": "United Kingdom",
"lat": 51.52,
"lon": -0.11,
"tz_id": "Europe/London",
"localtime_epoch": 1631360600,
"localtime": "2021-09-11 12:43"
},
"current": {
"last_updated_epoch": 1631359800,
"last_updated": "2021-09-11 12:30",
"temp_c": 21.0,
"temp_f": 69.8,
"is_day": 1,
"condition": {
"text": "Partly cloudy",
"icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
"code": 1003
},
"wind_mph": 11.9,
"wind_kph": 19.1,
"wind_degree": 250,
"wind_dir": "WSW",
"pressure_mb": 1017.0,
"pressure_in": 30.03,
"precip_mm": 0.0,
"precip_in": 0.0,
"humidity": 64,
"cloud": 50,
"feelslike_c": 21.0,
"feelslike_f": 69.8,
"vis_km": 10.0,
"vis_miles": 6.0,
"uv": 5.0,
"gust_mph": 10.5,
"gust_kph": 16.9
}
}
希望你能帮上忙:)
当用户点击按钮时,您实际上并没有更新状态。
button onClick={props.setPlaceName}
应该是这样的
button onClick={() => props.setPlaceName("Hello world")}
代码的相关部分在 Navbar
组件中:您没有向 setter 函数提供新的 placeName
。
因此,例如,您的 Navbar
组件应该看起来像这样:
function Navbar(props) {
// This state stores the updated input value
const [inputPlaceName, setInputPlaceName] = useState('');
// This function provides `setPlaceName` with the input value
function setGlobalPlaceName() {
props.setPlaceName(inputPlaceName);
}
return (
<form>
<input type="search" onChange={setInputPlaceName} />
<button onClick={setGlobalPlaceName} type="submit">
Search
</button>
</form>
);
}
然后,尝试订阅 Display
组件以更新 props.placeName
。这是通过将其添加到其 useEffect
:
useEffect(getWeatherInfo, [props.placeName])
正在运行的应用程序 https://codesandbox.io/s/jovial-pascal-kww85?file=/src/App.js
注:
- Prop 名称不能作为键,因为这个名称是保留的,用于唯一标识组件。(我使用 apikey 作为名称)
<Display apikey={key} placeName={placeName} />
- 在导航栏中,您必须使用另一种状态来跟踪文本框中的输入。
const [input, setInput] = useState("");
- 在 Navbar 中它应该是 onClick={() => props.setPlaceName(input)}
value={input} onChange={(e) => setInput(e.target.value)}
- 提交时的表单元素阻止默认不刷新页面。
<form className="d-flex" onSubmit={(e) => e.preventDefault()}>
- 在 props.placename 更改时显示调用 useEffect。
useEffect(async () => { getWeatherInfo(); }, [props.placeName]);