组件在react中状态改变时不重新呈现



我正面临这个错误从2天直接现在,我无法修复它!!所以,我创建一个天气应用程序反应使用https://www.weatherapi.com/这个api,我使用一个导航引导和我可以使用这个搜索选项如果用户搜索一个特定的状态,它将显示状态的数据,作为我工作与不同的组件保持App.jsApp.js清洁我宣布我可以通过按钮更新Navbar.js将作为支撑传递给Display.js(显示数据),但当我进入状态,点击提交,页面重新加载(我认为),它只是回到我原来的状态,作为一个假人。它不会用新数据渲染Display.js。我试图通过在浏览器上使用它来检查它,它返回响应。下面是代码。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
}
}

希望你能帮上忙:)

工作应用https://codesandbox.io/s/jovial-pascal-kww85?file=/src/App.js

注意:

  1. Prop名称不能是键,因为该名称保留用于唯一标识组件。(我使用apikey作为名称)
    <Display  apikey={key} placeName={placeName} />
    
  2. 在导航栏中,你必须使用另一个状态来跟踪文本框中的输入。
    const  [input, setInput] =  useState("");
    
  3. 在导航栏中应该是onClick={() =>props.setPlaceName(输入)}
    value={input}
    onChange={(e) =>  setInput(e.target.value)}
    
  4. 表单元素在提交防止默认不刷新页面。
    <form  className="d-flex"  onSubmit={(e) =>  e.preventDefault()}>
    
  5. 在显示调用useEffect时,道具。地名的变化。
    useEffect(async  ()  =>  {
    getWeatherInfo();
    },  [props.placeName]);
    

当用户点击按钮时,你实际上并没有更新状态。

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])

相关内容

最新更新