React数据加载以前的状态,而不是它应该加载的状态



我的应用程序有以下应用程序结构:app.js->过滤器.js->ListModal.js。对我来说,数据是一个JSON,包含作为键的表名,以及与这些键相对应的单独列。Filter.js包含一个搜索栏,单击后加载ListModal,根据搜索栏中键入的内容显示"表名"列表。在选择一个特定的表名后,该名称和相应的数据必须返回到App.js,然后将其传递给其他模块。

过滤器.js:

useEffect(() => {
const allTableName = Object.keys(data)
allTableNames.forEach((key,value)=>{
if(key.toUpperCase().includes(phyName.toUpperCase())){     //phyName contains the user input
searchedTables.push(key)
})
setSearchedTables(searchedTables)
}, [searchedTables])
const fetchTables = () => {    //Called upon clicking 'Submit' on the search bar
setSearchedTables([])
tableListModalShower()     //to show the modal
}
const setTable = (selectedTablename) => {
setTableDataToReturn(data[selectedTablename])    //variable to maintain which table's data to pass to parent App.js component
props.tableToPassInfo(selectedTablename, tableDataToReturn)
}
<ListModal searchedTables={searchedTables} onSelect={setTable}/>   // To load the modal

模态主体:

<Modal.body>
props.searchedTables.map(t=>(
<li key={t} value={t} onClick={() =>{ props.onSelect(t)}}>{t}</li>
)) 
</Modal.body>

App.js:

const [table, setTable] = useState({"tableName":"", "tableInfo":""})
const tableToPassInfo = (tablename, table) => {
setTable({"tableName":tablename, "tableInfo":table})
console.log(table)    //Here, I get the data for the table I searched for in the previous search, not the current one. Also, I do not get anything in the table name 
}
<FilterSection tableToPassInfo={tableToPassInfo}/>

我做错了什么?为什么我会得到我从"列表模式"中选择的内容的先前状态?感谢您的帮助。如果需要,很乐意提供更多详细信息!

我已经尽了最大努力根据注释更新代码

过滤器.js:

// I removed the useEffect on searchTables as it was set to run on change but was also changing within that method.

const fetchTables = () => {                    
const allTableName = Object.keys(data)
allTableNames.forEach((key,value)=>{
if(key.toUpperCase().includes(phyName.toUpperCase())){     
searchedTables.push(key);
}
});

setSearchedTables(searchedTables)
tableListModalShower()     //to show the modal
}

const setTable = (selectedTablename) => {
setTableDataToReturn(data[selectedTablename]);    
props.tableToPassInfo(selectedTablename, data[selectedTablename]);
}

<ListModal searchedTables={searchedTables} onSelect={setTable}/>   

模态主体:

<Modal.body>
props.searchedTables.map(t=>(
<li key={t} value={t} onClick={() =>{ props.onSelect(t)}}>{t}</li>
)) 
</Modal.body>

App.js:

const [table, setTable] = useState({"tableName":"", "tableInfo":""})
const tableToPassInfo = (tablename, tableinfo) => {
setTable({"tableName":tablename, "tableInfo":tableinfo})
console.log(tableinfo)    
}
<FilterSection tableToPassInfo={tableToPassInfo}/>

最新更新