如何判断Redux中dispatch和payload在useEffect中更新的useState的值

1l5u6lss  于 2023-04-06  发布在  其他
关注(0)|答案(2)|浏览(123)

标题不清楚。
我使用React和Redux-toolkit。我立即在useState set函数中引用了更新后的值,但我得到的是更新前的值。我知道useState更新不是立即执行的。
1.我们要做的是,我想立即引用事件中useState的更新值。
2. summary我想重新获取事件中的列表,根据重新获取后的列表数量(multipleList.length)进行判断。
3.Code

const [ multipleList, setMultipleList ] = useState<selectAddressList[]>([])
const selAddressList = useSelectAddressList();

// ★1
useEffect(() => {
 const setNewSelAddrList = () => {
  if (selAddressList && selAddressList.length > 0){
   const newList = [...selAddressList]
  
   // It has been confirmed that the updated address list is stored here.
  setMultipleList(newList);
 }
 }
 setNewSelAddrList();
}, [selAddressList])

// Combo Box Change Event
const onChangeAddr3 = async(rowData:string) => {

 // rowData contains a zip code.
 if (rowData != ''){

  // Get a list of addresses from a zip code
  await dispatch(fetchAsyncSelectedAddressList(rowData.toString()))        // ★2
     
  // ★I want to be judged by the number of updated address listings.★
  if (multipleList.length == 0){
   XXXXXXX
  }

 }
};
  1. supplement ★1地址列表(selAddressList)发生变化时触发事件,通过fetchAsyncSelectedAddressList更新selAddressList。★2通过Redux的Slice,从API中获取数据,更新地址列表(selAddressList)。
    我在onChangeAddr 3中创建了一个新数组,以此类推,但无法获得更新后的列表。
    谢谢大家。
    添加代码(代码在单独的文件中. useSelector从Store)
export function useSelectAddressList():selectAddressList[] {
  return useSelector((state:RootState) => state.selectAddressList.list);
}

export const fetchAsyncSelectedAddressList = createAsyncThunk<selectAddressList[], string>(
  "address/list",
  async (zipNo : string) => {
    const res = await axios.get<selectAddressList[]>(`${url}xxxx/xxx`,{
      params: {
        zipNo: zipNo,
      } as searchParams
    });
    return res.data;
  }
);

添加代码(代码显示屏幕)

<StyleFrom>
 <NativeSelect
  required
  disabled = {disableAddress}
  value = { add3Value }
  onChange = {e => onChangeAddr3(e.target.value as string)}
 >
  <option key={0} value=''>{''}</option>
  {
   addr3List?
   addr3List.map((row) => {
    return (
     <option key={row.zipNo}
             value={String(row.zipNo)}>
      {row.addrC}
     </option>
    )
   })
  : <option key={-1} value={0}>{'Failed'}</option>}
 </NativeSelect>
</StyleFrom>
ndh0cuux

ndh0cuux1#

我们通常使用它从store中检索redux-saga const updatedList = useSelector(state =〉state.savedMultipleList)中存储的状态。

4szc88ey

4szc88ey2#

我不知道这是否正确,但它已经解决了。
这取期望值。

await dispatch(fetchAsyncSelectedAddressList(rowData.toString())).then((res) => {
 // get count of list
 const newList = res.payload as selectAddressList[]

 if (newList.length == 0){
  // case 0 count of list
  alert(`no data`);
  return;
 }
 else { alert(newList.length) }
})

相关问题