- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 React 中使用 useState 和 useEffect 钩子(Hook)来渲染表单。但是当我使用 useEffect Hook 更新表单时。该表单不会重新呈现。
import React, { useState, useEffect } from 'react';
import { makeStyles } from "@material-ui/core/styles";
import GridItem from "components/Grid/GridItem.js";
import GridContainer from "components/Grid/GridContainer.js";
import Card from "components/Card/Card.js";
import CardHeader from "components/Card/CardHeader.js";
import CardBody from "components/Card/CardBody.js";
import Input from "components/UI/Input/Input";
import Button from "components/CustomButtons/Button.js";
import styles from "styles/styles";
import falconAPI from "falcon-api";
const useStyles = makeStyles(styles);
export default function AddWarehouse(props) {
const classes = useStyles();
// State management hooks
const [form, setForm] = useState({
warehouseType: {
elementType: 'select',
elementConfig: {
options: [
{ value: '4', displayValue: 'Showroom' }
]
},
value: '1',
validation: {},
valid: true
},
territory: {
elementType: 'select',
elementConfig: {
options: [
{ value: '1', displayValue: 'Kandy' },
{ value: '2', displayValue: 'Jaffna' },
{ value: '3', displayValue: 'Colombo' },
{ value: '4', displayValue: 'Galle' }
]
},
value: '1',
validation: {},
valid: true
},
name: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Name'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
address: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Address'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
telephone: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Telephone'
},
value: '',
validation: {
required: true,
},
valid: false,
touched: false
},
});
// Life cycle hooks
useEffect(() => {
falconAPI.post('/warehouse/type/all')
.then(response => {
const warehouseTypes = response.data.message;
const updatedWarehouseTypes = []
warehouseTypes.map(warehouseType => {
updatedWarehouseTypes.push({
value: warehouseType.id,
displayValue: warehouseType.name
});
})
const updatedForm = { ...form };
updatedForm.warehouseType.options = updatedWarehouseTypes;
setForm(updatedForm);
})
.catch(error => {
});
}, []);
const inputChangedHandler = (e) => {
}
const submitFormHandler = (e) => {
console.log(form);
}
const formElementsArray = [];
for (let key in form){
formElementsArray.push({
id: key,
config: form[key]
})
}
return (
<GridContainer>
<GridItem xs={12} sm={12} md={12}>
<Card>
<CardHeader color="success">
<h4 className={classes.cardTitleWhite}>{props.title}</h4>
</CardHeader>
<CardBody>
{formElementsArray.map(formElement => (
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
changed={(event) => inputChangedHandler(event, formElement.id)} />
))}
<Button onClick={submitFormHandler}>Add Model</Button>
</CardBody>
</Card>
</GridItem>
</GridContainer>
);
}
在 useEffect Hook 中,api 调用更新表单,因此重新渲染仓库类型选择输入,但选择输入不会重新渲染。可能是什么原因造成的。
最佳答案
您还需要复制嵌套值:
{
warehouseType: {
elementType: 'select',
elementConfig: {
options: [
{ value: '4', displayValue: 'Showroom' }
]
},
value: '1',
validation: {},
valid: true
},
...
const updatedForm = { ...form };
updatedForm.warehouseType.options = updatedWarehouseTypes;
setForm(updatedForm);
您还错过了其中的elementConfig
。 updatedForm.warehouseTypes.elementConfig.options
但是复制嵌套值仍然是一个好主意。
const updatedForm = {
...form,
warehouseType: {...form.warehouseType,
elementConfig: {...form.elementConfig,
options:updatedWarehouseTypes
}}};
关于javascript - 更改 useEffect 中的状态不会更改界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57889612/
我知道没有数组的 useEffect() 只在第一次渲染时运行回调。 那么useEffect(()=>{},[])和没有useEffect()的区别是什么。 我的意思是: function myCom
我的场景很少,我想了解渲染和性能方面的差异。 下面显示的示例是一个简单的函数,但请考虑一个更复杂的函数以及一个异步函数。 场景 1:定义函数并在 useEffect 中调用它。 useEffect((
我需要添加一些与 React 之外的对象交互的事件处理程序(以 Google map 为例)。 在这个处理函数内部,我想访问一些可以发送给这个外部对象的状态。 如果我将状态作为依赖项传递给效果,它可以
要限制 useEffect 在第一个渲染上运行,我们可以这样做: const isFirstRun = useRef(true); useEffect (() => { if (isF
我有一个产品组件,它显示某个类别的产品。CategoryId 从路由参数中获取,然后用户可以对产品进行分页。所以有2个useEffect,一个是改变categoryId的时候,另一个是改变当前页码的时
我有一个产品组件,它显示某个类别的产品。CategoryId 从路由参数中获取,然后用户可以对产品进行分页。所以有2个useEffect,一个是改变categoryId的时候,另一个是改变当前页码的时
我的状态宽度随着窗口大小的调整而变化,showFilters作为 Prop 从true变为false。我想在卸载时删除监听器。因此,我为每个条件使用了三个 useState。那么,我可以做任何重构来在
我正在开发一个基于对象键管理字符串数组的函数。假设它看起来像这样: import React, { useState, useEffect } from "react"; import FieldCo
新的 React Hooks 功能很酷,但有时会让我感到困惑。特别是,我将此代码包装在 useEffect Hook 中: const compA = ({ num }) => { const [
我想将其转换为 useEffect钩: 代码 componentDidMount () { this.messagesRef.on('child_added', snapshot => {
这是我的代码部分。一切正常,但 eslint 给出错误。 React Hook useEffect has missing dependencies: 'dispatch' and 'getData'
当组件安装时,我需要从两个 API 端点获取数据。现在我有: useEffect(() => { dispatch(loadSomeDataOne()); }, [dispatch])
当组件安装时,我需要从两个 API 端点获取数据。现在我有: useEffect(() => { dispatch(loadSomeDataOne()); }, [dispatch])
在 React DOCs 中,关于 useEffect() 钩子(Hook),我们得到: “使用 useEffect 安排的效果不会阻止浏览器更新屏幕。” Tip Unlike componentDi
我一直试图了解何时取消订阅(useEffect 中的回调)被准确调用。 这是codepen链接:https://codepen.io/deen_john/pen/eYmNdMy 代码 : const
当对状态、效果、上下文等使用钩子(Hook)时,我这样做: import React, { useState, useEffect, useContext } from 'react'; 但是,我注意
我正在尝试像下面这样的 useEffect 示例: useEffect(async () => { try { const response = await fetch(`ht
我在我的 React 应用中构建了一个简单的点赞、书签功能。 const [liked, setLiked] = useState(); const [bookmarked, setBookmarke
我想了解为什么在代码块的底部使用 useEffect,以及它的用途。我认为它与组件生命周期和避免无限循环有关,但我无法完全理解它并全面了解这一切。如果有人能向我解释幕后发生的事情,以及 useEffe
useEffect(() => { return history.replace({ pathname: "path/A", }); }, []); useEffe
我是一名优秀的程序员,十分优秀!