模态更新延迟在反应挂钩中设置新状态

modal update has delay to set new State in react hook

我在更新 editModal(反应 bootstrap 模态)时遇到了一些问题。 分派操作后它起作用了,我能够将单个宠物数据作为对象获取。 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>

就在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));