React状态异常排查:选中ListModal表项返回上一次搜索的旧数据
问题原因及修复方案
核心错误点
- React 状态更新为异步操作,Filter组件中
setTableDataToReturn执行后,立即读取tableDataToReturn拿到的是更新前的旧值:你在setTable函数里刚给tableDataToReturn赋值,同步调用props.tableToPassInfo传的还是上一次缓存的状态值,所以App拿到的永远慢一拍。 - useEffect存在语法错误+死循环风险:代码里定义的变量是
allTableName,遍历的时候写的是allTableNames多了个s,首先会直接报错;另外你把searchedTables放到useEffect的依赖数组里,回调里又调用setSearchedTables更新这个值,会导致无限触发useEffect执行。 - 冗余状态增加维护成本:不需要额外维护
tableDataToReturn状态,你已经拿到了选中的表名selectedTablename,直接从数据源data里取值传给父组件即可。
修复代码
Filter.js 修复
// 原错误useEffect直接删除,搜索逻辑移到提交触发函数中 const fetchTables = () => { //搜索栏点击提交时触发 const allTableNames = Object.keys(data) const matchedTables = allTableNames.filter(key => key.toUpperCase().includes(phyName.toUpperCase()) ) setSearchedTables(matchedTables) tableListModalShower() //唤起模态框 } const setTable = (selectedTablename) => { // 直接取当前选中表的对应数据,不需要走state中转 const currentTableData = data[selectedTablename] props.tableToPassInfo(selectedTablename, currentTableData) } <ListModal searchedTables={searchedTables} onSelect={setTable}/>
App.js 修复(如果需要实时打印最新状态,放到useEffect里监听)
const [table, setTable] = useState({"tableName":"", "tableInfo":""}) const tableToPassInfo = (tablename, tableData) => { setTable({"tableName":tablename, "tableInfo":tableData}) } // 要打印最新的table状态,用useEffect监听状态变化 useEffect(() => { console.log('当前选中的表数据:', table) }, [table]) <FilterSection tableToPassInfo={tableToPassInfo}/>
ListModal代码无需修改
内容的提问来源于stack exchange,提问作者Dhruv Kaushal
相关产品推荐
相关产品推荐

