反应:setState不会导致重新渲染吗?

如何解决反应:setState不会导致重新渲染吗?

我是React,JS,JSX的新手。

setNewWeather似乎没有正确更新天气状态,因为它是由初始值定义的,但是随后变为undefined。

因为它更新了,应该引起重新渲染;我看过很多关于此的文章,但他们建议喜欢,等待异步数据操作,但是据我了解,使用'.then'方法具有内在的功能吗? 还是涉及setNewWeather语法的另一个问题,例如它需要在内部使用一个函数而不只是一个字符串来更新状态?

我的代码:

import React,{ useState,useEffect } from 'react'
import axios from 'axios'

const Header = ({ text }) => <h1>{text}</h1>
const Header3 = ({ text }) => <h3>{text}</h3>
const Image = ({ source,alttext }) => <img src={source} alt={alttext} />
const Button = ({ onClick,text }) => (<button onClick={onClick}>{text}</button>)
const ListItem = ({ item }) => <li>{item}</li>
const List = ({ title,stuff }) => {
  return(
    <>
    < Header3 text={title} />
    <ul>
      {stuff.map((item,index) => < ListItem key={index} item={item} />)}
    </ul>
    </>)}
const Search = ({ text,value,onChange }) => {
  return (
    <>
    {text}
    <input value={value} onChange={onChange} />
    </>)}

const CountryMany = ({ country,handleClick }) => {
  return (
    <>
    <li>{country.name}</li>
    < Button onClick={handleClick(country.name)} text='Show' />
    </>)}

const CountryFound = ({ country,api_key,handleWeather,newWeather }) => {
  const countryFound = country[0]
  const params = {
    access_key: api_key,query: countryFound.capital
  }
  useEffect(() => {
    axios.get('http://api.weatherstack.com/current',{params})
         .then(response => {
          console.log('RESPONSE',response.data)
          handleWeather({ is: 'weather',data: response.data })
          console.log(newWeather)
          })},[params,newWeather,handleWeather])
  console.log('yo')
  console.log(newWeather)

  const languages = countryFound.languages.map(lang => lang.name)
  return (
    <>
    < Header text={countryFound.name} />
    <p>Capital: {countryFound.capital}</p>
    <p>Population: {countryFound.population}</p>
    < List title='Languages' stuff={languages} />
    < Header3 text='Flag' />
    < Image source={countryFound.flag} alttext='flag' />
    < Header3 text='Weather' />
    <ul>
      <li>Temperature: {newWeather}</li>
      <li> Image source= alttext=weather </li>
    </ul></>)}

const Countries = (props) => {
  console.log('COUNTRIES PROPS',props)
  console.log('WEATHER',props.newWeather)
  const countries = props.countries
  const foundCountries = countries.filter(country =>
    country.name.toLowerCase().includes(props.newSearch.toLowerCase()))
  if (foundCountries.length > 10 ) {
    return (<p>Too Many Matches,Keep Typing!</p>)}
  if (foundCountries.length > 1) {
    return (
        <ul>
        {foundCountries.map(country =>
        < CountryMany key={country.population} country={country} handleClick={props.handleClick} />)}
        </ul>)}
  if (foundCountries.length === 1) {
    return (
        <>
          <CountryFound api_key={props.a_k1} country={foundCountries}
            handleWeather={props.handleWeather} weather={props.newWeather} />
        </>)}
  return (<></>)}

const App = () => {
  const api_key = process.env.REACT_APP_API_KEY
  const [ countries,setCountries ] = useState([])
  const [ newSearch,setNewSearch ] = useState('')
  const [ newWeather,setWeather ] = useState({ is: 'no ewather' })
  const handleWeather = ( is,data ) => () => {
    setWeather( is,data )
    console.log('HEY HANDLEWEATHER',newWeather)}
  
  useEffect(() => {
    axios
      .get('https://restcountries.eu/rest/v2/all')
      .then(response => {
        setCountries(response.data)
      })},[])
  
  const handleClick = (value) => () => {
          setNewSearch(value)}
  const handleSearch = (event) => {
          setNewSearch(event.target.value)}
  
  return (
    <div>
      < Search text='Find A Country: ' value={newSearch} onChange={handleSearch}/>
      < Countries countries={countries} 
                  a_k1={api_key} 
                  handleWeather={handleWeather}
                  handleClick={handleClick} 
                  newSearch={newSearch}
                  newWeather={newWeather}
                   />
    </div>)}

export default App

/*
const Weather = ({ weather }) => {
    return (
    <>
    < Header3 text='Weather' />
    <ul>
      <li>Temperature: weather.temperature</li>
      <li> Image source= alttext=weather </li>
    </ul>
    </>)}
    */

谢谢!

编辑:状态正在更新,但只能通过形成无限循环来实现:

import React,handleClick }) => {
  return (
    <>
    <li>{country.name}</li>
    < Button onClick={handleClick(country.name)} text='Show' />
    </>)}

const CountryFound = ({ countryFound,newWeather }) => {
  const params = { access_key: api_key,query: countryFound.capital }
  useEffect(() => {
    axios.get('http://api.weatherstack.com/current',response.data)
          handleWeather(response.data)
          })})
  
  
  const languages = countryFound.languages.map(lang => lang.name)
  if (newWeather.length >  0 ){
    return (
      <>
      < Header text={countryFound.name} />
      <p>Capital: {countryFound.capital}</p>
      <p>Population: {countryFound.population}</p>
      < List title='Languages' stuff={languages} />
      < Header3 text='Flag' />
      < Image source={countryFound.flag} alttext='flag' />
      < Header3 text='Weather' />
      <ul>
      <li>Temperature/rendering {newWeather}</li>
      <li> Image source= alttext=weather </li>
      </ul></>)}
  return (
    <></>
  )}
  

const Countries = (props) => {
  console.log('COUNTRIES PROPS',props.newWeather)
  const foundCountries = props.countries.filter(country =>
    country.name.toLowerCase().includes(props.newSearch.toLowerCase()))
  if (foundCountries.length > 10 ) {
    return (<p>Too Many Matches,Keep Typing!</p>)}
  if (foundCountries.length > 1) {
    return (
        <ul>
        {foundCountries.map(country =>
        < CountryMany key={country.population} country={country} handleClick={props.handleClick} />)}
        </ul>)}
  if (foundCountries.length === 1) {
    return (
        <>
          <CountryFound api_key={props.a_k1} countryFound={foundCountries[0]}
            handleWeather={props.handleWeather} newWeather={props.newWeather} />
        </>)}
  return (<></>)}

const App = () => {
  const api_key = process.env.REACT_APP_API_KEY
  const [ countries,setNewSearch ] = useState('af')
  const [ newWeather,setWeather ] = useState([])
  const handleClick = (value) => () => {
        setNewSearch(value)}
  const handleSearch = (event) => {
        setNewSearch(event.target.value)}

  useEffect(() => {
    axios
      .get('https://restcountries.eu/rest/v2/all')
      .then(response => {
        setCountries(response.data)
      })},[])
  return (
    <div>
      < Search text='Find A Country: ' value={newSearch} onChange={handleSearch}/>
      < Countries countries={countries} 
                  a_k1={api_key} 
                  handleWeather={setWeather}
                  handleClick={handleClick} 
                  newSearch={newSearch}
                  newWeather={newWeather}
                   />
    </div>)}

export default App

最终编辑:已解决!

以下标记的解决方案解决了初始问题,但产生了无限循环。我已经整顿了整件事,尽管我还不太了解它是如何改变的。

import React,index) => < ListItem key={index} item={item} />)}
    </ul>
    </>)}

const Search = ({ text,newWeather }) => {
  useEffect(() => {
    axios.get(`https://api.weatherbit.io/v2.0/current?city=${countryFound.capital}&key=${api_key}`)
          .then(response => {
          handleWeather(response.data.data[0])
          })})
  const languages = countryFound.languages.map(lang => lang.name)
  if (newWeather > '' ) {
    const capital = countryFound.capital
    const weatherTitle = `Weather in: ${capital}`
    const weatherImage = `https://www.weatherbit.io/static/img/icons/${newWeather.weather.icon}.png`
    return (
      <>
      < Header text={countryFound.name} />
      <p>Capital: {capital}</p>
      <p>Population: {countryFound.population}</p>
      < List title='Languages' stuff={languages} />
      < Header3 text='Flag' />
      < Image source={countryFound.flag} alttext='flag' />
      < Header3 text={weatherTitle} />
      < Image source={weatherImage} alttext='weather' />
      <ul>
      <li>Temperature: {newWeather.temp} degrees Celsius</li>
      <li>Wind: {newWeather.wind_spd} mph towards {newWeather.wind_cdir}</li>
      </ul></>)}
  return (<><p>Loading...</p></>)}
  
const Countries = (props) => {
  const foundCountries = props.countries.filter(country =>
    country.name.toLowerCase().includes(props.newSearch.toLowerCase()))
  if (foundCountries.length > 10 ) {
    return (<p>Too Many Matches,Keep Typing!</p>)}
  
  if (foundCountries.length > 1) {
    return (
        <ul>
        {foundCountries.map(country =>
        < CountryMany key={country.population} 
                      country={country} 
                      handleClick={props.handleClick} />)}
        </ul>)}
  
  if (foundCountries.length === 1) {
    return (<>
          <CountryFound api_key={props.a_k1} countryFound={foundCountries[0]}
            handleWeather={props.handleWeather} newWeather={props.newWeather} />
            </>)}
  return (<></>)}

const App = () => {
  const api_key = process.env.REACT_APP_API_KEY
  const [ countries,setWeather ] = useState('')
  const handleClick = (value) => () => {
        setNewSearch(value)}
  const handleSearch = (event) => {
        setNewSearch(event.target.value)}

  useEffect(() => {
    axios
      .get('https://restcountries.eu/rest/v2/all')
      .then(response => {
        setCountries(response.data)
      })},[])

  return (
    <div>
      < Search text='Find A Country: ' value={newSearch} onChange={handleSearch}/>
      < Countries countries={countries} 
                  a_k1={api_key} 
                  handleWeather={setWeather}
                  handleClick={handleClick} 
                  newSearch={newSearch}
                  newWeather={newWeather}
                   />
    </div>)}

export default App

解决方法

问题

handleWeather定义为带有两个参数

const handleWeather = ( is,data ) => () => {
  setWeather( is,data )
  console.log('HEY HANDLEWEATHER',newWeather)
}

但是当您调用它时,您只能传递一个参数

handleWeather({ is: 'weather',data: response.data })

此外,反应状态更新是异步的,并且在渲染周期之间是批量处理的,因此尝试在入队后立即控制台日志状态只会记录当前状态。

解决方案

您应该选择接受两个参数并创建您想要的状态对象,或者将要存储的已创建对象始终传递给它。以下将使用后者。

const handleWeather = (newWeather) => () => setWeather(newWeather);

注意:目前,handleWeather只是代理newWeather对象,因此较小的优化可能不是 代理,因为函数签名匹配,即const handleWeather = setWeather,或者直接传递setWeather作为回调。

<Countries
  countries={countries} 
  a_k1={api_key} 
  handleWeather={setWeather} // <-- directly pass state update function
  handleClick={handleClick} 
  newSearch={newSearch}
  newWeather={newWeather}
/>

使用效果来记录更新的newWeather,并使用newWeather作为依赖项。

useEffect(() => {
  console.log('HEY HANDLEWEATHER',newWeather)
},[newWeather]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res