React中this.state.series函数内有值但render为空,是否与componentDidMount有关?
你遇到的问题并非componentDidMount()的执行逻辑导致,核心问题是你违反了React state的修改规则,以及对setState的异步特性理解有误。
核心问题说明
- 禁止直接修改state的值:你代码中
this.state.series.push(a.count)属于直接操作state中的数组,React不会监听这种直接修改的操作,因此不会触发组件重渲染,render方法自然拿不到更新后的series值。你在fetch回调中打印的有值数组是你手动修改后的内存值,并未同步到React的渲染流程中。 setState是异步更新操作:你执行this.setState({results:response})后立刻读取this.state.results,拿到的还是更新前的旧值,这部分逻辑本身也不符合setState的使用规范。- 额外小问题:你请求头里的
Content-Type值写错了,应该是application/json而非application.json。
修正后的代码
constructor(props){ super(props); this.state = { series: [], results: [] } } GetTransaction = () => { const APIURL = "http://10.0.2.2:80/api/getTransaction.php"; const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' }; fetch(APIURL, { method: 'POST', headers: headers, }) .then((response) => response.json()) .then((response) => { // 直接基于接口返回值生成新的series数组 const newSeries = response[0].map(a => a.count); // 统一用setState更新所有state,触发重渲染 this.setState({ results: response, series: newSeries }); }) .catch((error) => { alert("Error"+error); }); } componentDidMount(){ this.GetTransaction(); } render(){ console.log(this.state.series) // 渲染逻辑自行补充,首次渲染series为空,接口返回后会自动重渲染拿到最新值 }
控制台输出现象解释
你看到的前7个空数组都是render方法打印的:第一次是组件初始挂载时的渲染输出,后续几次是你原有代码中调用this.setState({results:response})触发的重渲染输出,这时候因为series没有通过setState更新,所以一直是空值。最后一个带内容的数组是你fetch回调里的手动打印,不属于render阶段的输出。
内容的提问来源于stack exchange,提问作者Unknown
相关产品推荐
相关产品推荐

