【问题标题】:modal update has delay to set new State in react hook模态更新延迟在反应钩子中设置新状态
【发布时间】:2021-09-01 14:58:32
【问题描述】:

我在更新 editModal(反应引导模式)时遇到了一些问题。 在调度它工作的动作之后,我能够将单个宠物数据作为对象获取。 and redux dev tools confirms that 但是模态在第一次尝试时没有打开,我需要再次单击(编辑按钮:不管哪个)以显示填充的输入数据,并且每次我单击第一个宠物或第二个宠物的编辑按钮时它不会t 更新模态并显示与先前单击的编辑相关的数据 and as you see I clicked the second edit and data has fetched as redux dev tools shows correctly but Modal still shows first pet details

感谢您的帮助:)

这是我的代码

const PetScreen = () => {
      const dispatch = useDispatch()

    //part of state that comes from store.js
    const petDetailByUser = useSelector((state) => state.petDetailByUser)


//when action dispatch petDetails fills with single pet Details ex:_id,editPetName,...
    const { petDetailLoading, petDetails } = petDetailByUser
       

    const [editPetName, setEditPetName] = useState('')

    //edit button dispatch getPetDetail and get pet data as an object
     const editButtonHandler = (id) => {
        dispatch(getPetDetails(id))
        if (petDetails) {
          setEditPetName(petDetails.editPetName)
    //shows edit modal
         handleEditShow()
        }
      }
      
      
     //this field is inside react modal body 
     <Form.Control
          type='text'
          placeholder='Pet Name'
          name='editPetName'
          value={editPetName}
          onChange={(e) => setEditPetName(e.target.value)}
           >
    </Form.Control>

【问题讨论】:

    标签: javascript reactjs react-hooks bootstrap-modal setstate


    【解决方案1】:

    就在dispatch(getPetDetails(id)) 之后,editPetName 变量还没有被刷新,所以它包含了前一个宠物的名字。

    petDetails 更新时,您可以使用更新editPetName 的效果来修复它。

    const petDetailByUser = useSelector((state) => state.petDetailByUser)
    const { petDetailLoading, petDetails } = petDetailByUser;
    
    const [editPetName, setEditPetName] = useState('');
    
    useEffect(() => {
      if (petDetails) {
        setEditPetName(petDetails.editPetName);
        handleEditShow();
      }
    }, [petDetails]);
    
    const editButtonHandler = (id) => dispatch(getPetDetails(id));
    

    【讨论】:

    • 它有效......谢谢你,亲爱的奥利维尔 :) .....上帝保佑你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2021-05-19
    • 1970-01-01
    • 2021-06-15
    • 2021-06-02
    • 2020-11-30
    • 2021-01-31
    相关资源
    最近更新 更多