React页面刷新后自定义hook状态丢失但Redux状态仍存在如何解决
问题原因
- React的
useState仅会在Hook首次初始化时读取传入的初始值,后续入参发生变化不会自动同步到本地状态 - 页面刷新后组件首次渲染时,异步拉取设备详情的请求还未返回,Redux中的
selectedDevice还是初始空值,此时useDevice内部的device状态就被初始化为空。等接口请求完成、Redux中的selectedDevice更新后,useState不会主动响应这个变化,就出现了Redux有值但Hook内状态为空的情况。
解决方法
方案1:自定义Hook内监听入参同步状态(推荐)
在useDevice中新增useEffect监听传入的初始值变化,有有效值时同步更新内部状态,修改后的useDevice代码如下:
import { useState, useEffect } from "react"; import { useDispatch } from "react-redux"; import axios from "axios"; import getDevices from "../actions/devicesAtions"; import { isPositiveInteger, FORM_FIELDS } from "../helper"; export default function useDevice(value) { const dispatch = useDispatch(); const [device, setDevice] = useState(value); const [msg, setMsg] = useState(""); // 新增:监听入参value变化,同步更新本地device状态 useEffect(() => { // 可根据业务调整判断逻辑,避免空值覆盖用户已编辑的本地状态 if (value && JSON.stringify(value) !== JSON.stringify(device)) { setDevice(value); } }, [value]); const saveDeviceChange = ({ target }) => { const { name, value } = target; setDevice({ ...device, [name]: value }); setMsg(""); }; const saveDeviceSubmit = async ( e, axiosMethod, selectedUrl, newDevice = device ) => { e.preventDefault(); const { system_name, type, hdd_capacity } = device; if (!system_name || !type || !hdd_capacity) { setMsg( `Please fill out ${!system_name ? FORM_FIELDS.SYS_NAME : ""} ${ !type ? FORM_FIELDS.DEVICE_TYPE : "" } ${!hdd_capacity ? FORM_FIELDS.HDD_CAPACITY : ""}!` ); return false; } if (!isPositiveInteger(hdd_capacity)) { setMsg( "Please enter a positive number or round it to the nearst whole number!" ); return false; } try { await axios({ method: axiosMethod, url: selectedUrl, data: device, headers: { "Content-Type": "application/json" } }); dispatch(getDevices()); } catch (err) { console.log(err); } setMsg("Changes have been made!"); setDevice(newDevice); }; return { device, setDevice, msg, setMsg, saveDeviceChange, saveDeviceSubmit }; }
方案2:父组件等待数据加载完成再渲染
在EditDeviceWrapper中加加载判断,等Redux中selectedDevice有有效值后再初始化useDevice和渲染表单:
import React, { useEffect } from "react"; import { useSelector, useDispatch } from "react-redux"; import { useParams } from "react-router-dom"; import ReusedForm from "./ReusedForm"; import useDevice from "./useDevice"; import { getDeviceDetails } from "../actions/devicesAtions"; export default function EditDeviceWrapper() { const dispatch = useDispatch(); const { selectedDevice } = useSelector((state) => state.allDevices); const { id } = useParams(); useEffect(() => { dispatch(getDeviceDetails(id)); }, [id, dispatch]); // 新增:数据未加载完成时显示加载态 if (!selectedDevice?.id) return <div>加载中...</div> const { device, msg, saveDeviceChange, saveDeviceSubmit } = useDevice( selectedDevice ); console.log(device, selectedDevice); return ( <> <p className="form-msg">{msg}</p> <ReusedForm saveDeviceSubmit={(e) => saveDeviceSubmit(e, "put", `http://localhost:3000/devices/${id}`) } selectDeviceValChange={saveDeviceChange} heading="Update Device" system_name={device.system_name} type={device.type} hdd_capacity={device.hdd_capacity} /> <p>{id}</p> </> ); }
两种方案可任选其一,也可同时使用做双重保障。
内容的提问来源于stack exchange,提问作者Angie
相关产品推荐
相关产品推荐

