我要做什么:尝试输入一个人的名字和姓氏,并使用redux全局状态管理在下面显示所有输入的名字。
当我试图通过在输入字段中输入数据来创建新对象时,第一个项目在视图页面和控制台日志上都显示为空,从第二个项目开始,所有项目都正确显示。我以前遇到过这个错误,但无法修复。
实际页面:
import {useDispatch} from 'react-redux';
import {useState} from 'react';
const Inc = ()=>{
const[data, setData] = useState({});
const[firstName, setFirstName] = useState('');
const[lastName, setLastName] = useState('');
const dispatch = useDispatch();
const newData={
first_name: "",
last_name : ""
}
const handleFieldFirst=async (e)=>{
await setFirstName(e.target.value);
}
const handleFieldLast= async (e)=>{
await setLastName(e.target.value);
}
const handler = async (e)=>{
e.preventDefault();
newData.first_name = firstName ;
newData.last_name = lastName ;
await setData(newData);
console.log(data);
dispatch({type: 'INC', payload : data});
document.getElementById("form1").reset();
}
return(
<form id="form1" type ="submit" name="login" >
<input onChange={e => handleFieldFirst(e)} name="first" type="text" placeholder="First name"></input>
<input onChange={e => handleFieldLast(e)} name="last" type="text" placeholder="Last name"></input>
<button onClick={e => handler(e)}>Submit</button>
</form>
);
}
export default Inc;
查看页面
import {useSelector} from 'react-redux';
const Disp = ()=>{
const count = useSelector(state => state.counterReducer);
return(
<div>
{count.map((d) => <li key={d.last_name}>{d.first_name} {d.last_name}</li>)}
</div>
);
}
export default Disp;
在此处输入图像描述
首先,您必须更改代码。只有当函数返回promise 时,才必须使用async
和await
import { useState } from "react";
import { useDispatch } from "react-redux";
const Inc = () => {
const [data, setData] = useState({
firstName: "",
lastName: "",
});
const dispatch = useDispatch();
const handler = (e) => {
e.preventDefault();
dispatch({ type: "INC", payload: data });
setData({
firstName: "",
lastName: "",
});
};
return (
<form id="form1" type="submit" name="login">
<input
onChange={(e) =>
setData({
...data,
firstName: e.target.value,
})
}
name="first"
type="text"
placeholder="First name"
value={data.firstName}
/>
<input
onChange={(e) =>
setData({
...data,
lastName: e.target.value,
})
}
name="last"
type="text"
placeholder="Last name"
value={data.lastName}
/>
<button onClick={handler}>Submit</button>
</form>
);
};
export default Inc;
默认情况下,useSelector
将返回默认状态(您没有附加reducer代码,所以我假设reducer返回默认状态(,因此添加一个条件以仅在数组长度大于0时渲染<li>....</li>
。