当前位置: 首页 > 知识库问答 >
问题:

react.js - react useState 拿不到最新的值怎么解决?

薛阳荣
2024-10-17

代码情景是在 useEffect 中请求字典返回 Array 后通过 setDeviceType 赋值, 但是在 antd table 组件的 render 拿不到字典最新返回的 Array, 导致 dictFeedback 方法中 deviceType 为空 Array ......
又用了 useRef , 字典返回 res 赋值给 deviceTypeRef.current, 但又不重新渲染dom 导致 select 组件不能正常使用 ......

下面为源码, 请问大佬们有什么好的解决办法, 能在table组件的render中获取到最新的Array?

const [deviceType, setDeviceType] = useState([])
useEffect(() => {
    // dictionaries 方法是封装的字典请求
   dictionaries('01').then(res => setDeviceType(res))
 }, [])
const columns = [
  //  dictFeedback 方法返回 text在字典中对应的字段
  {title: '设备类型',dataIndex: 'deviceType',key: 'deviceType', render: (text) => dictFeedback(deviceType,text)},
];
<Select placeholder='请选择设备类型' allowClear>
        {deviceType.map((item, index) => <Option value={item.codeNum} key={index}>{item.name}</Option>)}
</Select>
<Table dataSource={dataSource} columns={columns} />

共有2个答案

严昀
2024-10-17
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Table, Select } from 'antd';

const YourComponent = () => {
  const [deviceType, setDeviceType] = useState([]);
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    dictionaries('01').then(res => {
      setDeviceType(res);
      fetchData(res).then(data => setDataSource(data));
    });
  }, []);

  const dictFeedback = useCallback((deviceType, text) => {
    const item = deviceType.find(dt => dt.codeNum === text);
    return item ? item.name : text;
  }, []);

  const columns = useMemo(() => [
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      render: (text) => dictFeedback(deviceType, text),
    },
    // 其他列
  ], [deviceType, dictFeedback]);

  return (
    <>
      <Select placeholder='请选择设备类型' allowClear>
        {deviceType.map((item) => (
          <Select.Option value={item.codeNum} key={item.codeNum}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
      <Table dataSource={dataSource} columns={columns} />
    </>
  );
};

export default YourComponent;
晏正豪
2024-10-17

const columns = useMemo(() => ([
// dictFeedback 方法返回 text在字典中对应的字段
{title: '设备类型',dataIndex: 'deviceType',key: 'deviceType', render: (text) => dictFeedback(deviceType,text)},
]), [deviceType]);

 类似资料: