You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目axios请求后调用setState赋值数组返回空值问题咨询

问题原因

  1. React状态更新是异步操作
    你调用setSearchValues(res)之后,React不会立刻更新searchValues的状态值,你在then里同步打印searchValues拿到的还是更新前的旧值(也就是初始的空数组),所以看起来赋值没生效,实际状态已经进入了更新队列,下一次组件渲染的时候就会拿到新值。
  2. then的回调写法错误
    你现在的写法是把console.log('restl', searchValues)放在了then的第二个参数位置(也就是请求失败的错误回调位),而且没有包裹在函数里,会在axios请求发起的瞬间就同步执行,根本等不到请求返回结果。
  3. 接口返回值取值错误
    axios请求返回的响应是封装对象,实际的接口返回内容存在res.data属性里,你直接把整个res赋值给状态,不符合Autocomplete组件options参数的数组要求,也会导致下拉项不显示。
  4. 事件绑定位置不合理
    你把onFocus绑在了整个Form组件上,只要表单内任意元素获得焦点都会触发请求,建议直接绑定到对应输入字段上更精准。

修复后代码示例

const url = 'http://localhost:3000';
const [searchValues, setSearchValues] = useState([]);

// 监听状态变化验证更新结果
useEffect(() => {
  console.log('更新后的下拉选项:', searchValues);
}, [searchValues])

const getDropdownItems = (event) => {
    console.log('触发字段id:', event.target.getAttribute('id'));
    axios
        .get(`${url}/${event.target.getAttribute('id')}`)
        .then((res) => {
            // 取实际接口返回的数组赋值
            setSearchValues(res.data);
            // 要查看请求结果直接打印接口返回值,不要打印未更新的state
            console.log('接口返回结果:', res.data);
        })
        .catch(err => console.log('请求报错:', err))
};
        
render(
    <Form
        onSubmit={formik.handleSubmit}
    >
        <Row>
            <Col xs="auto" style={minWidth}>
                <FastField
                    id="DatumEingabe"
                    name="DatumEingabe"
                    component={Autocomplete}
                    label="Datum-Eingabe"
                    type="text"
                    options={searchValues}
                    // 把聚焦事件绑定到对应输入字段
                    onFocus={getDropdownItems}
                />
            </Col>
        </Row>
    </Form>
)

内容的提问来源于stack exchange,提问作者Severin Koch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:54:00