reactjs - 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>
)
}
当我添加项目时,组件在列表中显示新项目不到一秒钟,直到重新渲染准确,然后它又回到旧状态......
解决方案
问题是提交刷新,因此您需要通过执行 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;
}
推荐阅读
- javascript - 如何在tinymce中禁用复制/粘贴
- java - 将 java 命令转换为 maven 配置文件时出现问题
- laravel - Laravel Nova Metric 卡片显示自定义标签
- android - 将数据从子活动 onActivityResult() 发送到父活动 onActivityResult()
- c# - 如何使用 xamarin.ios 创建圆形脉冲动画?
- python - 假设检验的表格设置 - 带有 t 检验和 WMW 检验的交叉表
- wordpress-gutenberg - 我没有在古腾堡块中添加样式表
- angular - 尝试使用已破坏的视图:detectChanges 事件,尽管视图已分离
- python - 在熊猫数据框中作为某些值的列数
- javascript - 如何在 ReactJS 中使用 screen.width 值?