首页 > 解决方案 > React setState 重新渲染旧状态

问题描述

这是我的父组件:

import React, { useState } from 'react';
import { TextField } from '../textfield';


export const List = () => {

  const [list, setList] =useState<string[]>(["bananas", "apples"]);

  return (
    <div>
       <h1>
        Shopping List
      </h1>

      <TextField createList={(userInput: any) => setList([...list,userInput])} />

      <ul>
     {list?list.map((item: string, id: number) => (
            <li key={id}><input type="checkbox"/>{item}</li>
          )): "list is still empty, lets add something"}
      </ul>
     
    </div>
  )
}

它从子组件的形式中获取列表的新项:

import React, { useState } from 'react';


interface Props {
  createList: any;
}

export const TextField: React.FC<Props>=({createList})  =>{

const [userInput, setUserInput] =useState<string | null>();

  return (
    <div>
    <form onSubmit= {() => createList(userInput)}>
       <input onChange={(e) => setUserInput(e.target.value)}  placeholder ="add something to the list.."/>
      <button type="submit">Add to list</button>
   </form>
   </div>
  )
}

当我添加项目时,组件在列表中显示新项目不到一秒钟,直到重新渲染准确,然后它又回到旧状态......

标签: reactjs

解决方案


问题是提交刷新,因此您需要通过执行 e.preventDefault() 来防止它

  const handleSubmit = (e:FormEvent<HTMLFormElement>) => {
      e.preventDefault()
      createList(userInput)
  }
<form onSubmit= {(e) => handleSubmit(e)}>

另一件事是,当您使用 TypeScript 时,请尝试更具体地了解您使用的类型,如下所示:

interface Props {
  createList: (a:any)=>void;//instead of any
}

只是为了注意:在 TypeScript 中,您需要更具体地说明您的类型,而不是像这样抛出任何东西:

 interface Props {
  createList: any;
}

因为现在您可以在此处插入您想要的所有内容,并在此处插入 TypeScript 以防止这种情况发生,并让您决定特定的类型,因此如果您插入错误的类型,代码将不会运行。尝试这样做:

interface Props {
  createList: (a:any)=>void;
}

推荐阅读