Reactjs useState钩子在页面刷新时丢失地图数据
我正在使用useState钩子添加产品表单。 刷新页面时,不会显示字段类别的数据(我尝试显示类别,因此用户可以从列表中选择类别以创建该类别的产品)。但是数据保存在redux存储中: 它仅在我使用react router()转到另一个页面然后返回时显示 这是我的代码:Reactjs useState钩子在页面刷新时丢失地图数据,reactjs,redux,use-state,Reactjs,Redux,Use State,我正在使用useState钩子添加产品表单。 刷新页面时,不会显示字段类别的数据(我尝试显示类别,因此用户可以从列表中选择类别以创建该类别的产品)。但是数据保存在redux存储中: 它仅在我使用react router()转到另一个页面然后返回时显示 这是我的代码: export const AddProduct = () => { const dispatch = useDispatch(); const userId = useSelector(state =>
export const AddProduct = () => {
const dispatch = useDispatch();
const userId = useSelector(state => state.auth.userId);
const categories = useSelector(state => state.categories.categories);
const [avatar, setAvatar] = React.useState('');
React.useEffect(() => {
dispatch(categoriesActions.fetchCategories());
}, [dispatch]);
const [orderForm, setOrderForm] = React.useState({
title: {
elementType: 'input',
label: 'Title',
elementConfig: {
type: 'text',
placeholder: 'Title'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
price: {
elementType: 'input',
label: 'Price',
elementConfig: {
type: 'text',
placeholder: 'Price'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
description: {
elementType: 'textarea',
label: 'Description',
elementConfig: {
type: 'text',
placeholder: 'Description'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
category: {
elementType: 'select',
label: 'Select category',
elementConfig:
categories.map(category => (
<option key={category._id} value={category.title}>
{category.title}
</option>))
,
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
});
const [formIsValid, setFormIsValid] = React.useState(false);
const addProductData = event => {
event.preventDefault();
const formData = {};
for (let formElementIdentifier in orderForm) {
formData[formElementIdentifier] = orderForm[formElementIdentifier].value;
}
const product = {
userId: userId,
title: formData.title,
price: formData.price,
description: formData.description,
category: formData.category
}
dispatch(productsActions.addProduct(product));
}
const inputChangedHandler = (event, inputIdentifier) => {
const updatedFormElement = updateObject(orderForm[inputIdentifier], {
value: event.target.value,
valid: checkValidity(
event.target.value,
orderForm[inputIdentifier].validation
),
touched: true
});
const updatedOrderForm = updateObject(orderForm, {
[inputIdentifier]: updatedFormElement
});
let formIsValid = true;
for (let inputIdentifier in updatedOrderForm) {
formIsValid = updatedOrderForm[inputIdentifier].valid && formIsValid;
}
setOrderForm(updatedOrderForm);
setFormIsValid(formIsValid);
};
const formElementsArray = [];
for (let key in orderForm) {
formElementsArray.push({
id: key,
config: orderForm[key]
});
}
let form = (
<form onSubmit={addProductData}>
{formElementsArray.map(formElement => (
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
label={formElement.config.label}
hint={formElement.config.hint}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={event => inputChangedHandler(event, formElement.id)}
/>
))}
<Button btnType="Success" disabled={!formIsValid}>ORDER</Button>
</form>
)
return (
<div class="wrapper">
<Header />
<article class="main">
<div class="row">
<div class="item--1-4 image-block">
<div class="product-image-group">
<img class="product-image-big" src={`/${avatar}`} />
<hr class="border-divider" />
<input type="file" onChange={e => setAvatar(e.target.files[0].name)} name="imageUrl" id="imageUrl" />
</div>
</div>
<div class="item--3-4">
<div class="item-title">
<h3>Add product</h3>
<hr class="border-divider" />
</div>
{form}
</div>
</div>
</article>
<LeftMenu />
</div>
)
}
export const AddProduct=()=>{
const dispatch=usedpatch();
const userId=useSelector(state=>state.auth.userId);
const categories=useSelector(state=>state.categories.categories);
const[avatar,setAvatar]=React.useState(“”);
React.useffect(()=>{
分派(categoriesActions.fetchCategories());
},[发送];
const[orderForm,setOrderForm]=React.useState({
标题:{
elementType:'输入',
标签:“标题”,
元素配置:{
键入:“文本”,
占位符:“标题”
},
值:“”,
验证:{
必填项:true
},
有效:假,
感动:错
},
价格:{
elementType:'输入',
标签:“价格”,
元素配置:{
键入:“文本”,
占位符:“价格”
},
值:“”,
验证:{
必填项:true
},
有效:假,
感动:错
},
说明:{
elementType:'textarea',
标签:“说明”,
元素配置:{
键入:“文本”,
占位符:“说明”
},
值:“”,
验证:{
必填项:true
},
有效:假,
感动:错
},
类别:{
elementType:'选择',
标签:“选择类别”,
元素配置:
categories.map(category=>(
{category.title}
))
,
值:“”,
验证:{
必填项:true
},
有效:假,
感动:错
},
});
const[formIsValid,setFormIsValid]=React.useState(false);
const addProductData=事件=>{
event.preventDefault();
const formData={};
for(让formElementIdentifier出现在订单中){
formData[formElementIdentifier]=orderForm[formElementIdentifier]。值;
}
常数乘积={
userId:userId,
标题:formData.title,
价格:formData.price,
description:formData.description,
类别:formData.category
}
发货(productsActions.addProduct(product));
}
常量inputChangedHandler=(事件,inputIdentifier)=>{
const updatedFormElement=updateObject(订单[inputIdentifier]{
值:event.target.value,
有效:检查有效性(
event.target.value,
订单[inputIdentifier]。验证
),
感动:真的
});
常量UpdateOrderForm=updateObject(orderForm{
[inputIdentifier]:updatedFormElement
});
让formIsValid=true;
for(以updatedOrderForm格式输入标识符){
formIsValid=UpdateOrderForm[inputIdentifier]。有效(&formIsValid);
}
setOrderForm(更新的OrderForm);
setFormIsValid(formIsValid);
};
常量formElementsArray=[];
for(在订单中输入){
formElementsArray.push({
id:钥匙,
config:orderForm[key]
});
}
设形式=(
{formElementsArray.map(formElement=>(
inputChangedHandler(事件,formElement.id)}
/>
))}
命令
)
返回(
setAvatar(e.target.files[0].name)}name=“imageUrl”id=“imageUrl”/>
添加产品
{form}
)
}
这是我的代码中与该选择字段相关的行:
elementConfig:
categories.map(category => (
<option key={category._id} value={category.title}>
{category.title}
</option>))
elementConfig:
categories.map(category=>(
{category.title}
))
这是因为组件第一次加载时,类别中没有任何内容
,并且当设置了类别时,您不会再次设置订单
数据。这被称为“过时道具”
您需要执行以下操作:
useEffect(() => {
setOrderForm((oldValue) => ({
...oldValue,
category: {
...oldValue.category,
elementConfig: categories.map((category) => (
<option key={category._id} value={category.title}>
{category.title}
</option>
)),
},
}));
}, [categories])
useffect(()=>{
setOrderForm((旧值)=>({
…旧价值,
类别:{
…oldValue.category,
elementConfig:categories.map((category)=>(
{category.title}
)),
},
}));
},[类别])
这样,每次更改类别
数据时,您都会相应地更改订单
状态