反应setState重新呈现旧状态

时间:2020-11-10 11:34:43

标签: reactjs

这是我的父组件:

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

当我添加项目时,组件会在列表中显示新项目的时间少于一秒钟,直到重新渲染accurs,然后又恢复为旧状态...

1 个答案:

答案 0 :(得分:0)

问题在于提交刷新,因此您需要通过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;
}