React Native状态变量更新后视图无法刷新问题该如何解决?
问题原因
- React 中不允许直接修改 state 值:你写的
this.state.name = responseJson[0].name是直接赋值操作,不会触发 React 的重新渲染逻辑,只有调用this.setState()方法更新状态,才会通知 React 重新执行 render 方法刷新视图。 - 网络请求放置位置错误:你把
fetch请求直接写在了render方法中,render 方法会在每次状态更新、组件重渲染时执行,如果在这里发请求,请求成功调用 setState 后又会触发重渲染、再发起新请求,最终会陷入无限循环。你现在的日志只看到一次请求是因为还没触发重渲染,一旦修复了 setState 的问题,马上就会出现无限请求的bug。
修复方案
- 把 fetch 请求移到组件的
componentDidMount生命周期钩子中,这个钩子只会在组件第一次挂载完成后执行一次,不会重复触发。 - 把直接赋值 state 的代码替换成
this.setState()的方式更新状态。
修复后完整代码:
import React, { Component } from 'react'; import { Text, View } from 'react-native'; export default class WhatsDes extends Component { constructor(props) { super(props); this.state = {name:'', email:''}; } // 组件挂载完成后仅执行一次网络请求 componentDidMount() { const url = 'http://192.168.1.13:8091/employees'; fetch(url) .then(response => response.json()) .then(responseJson => { console.log('ok 1: '+ JSON.stringify(responseJson)); console.log('ok 2: '+responseJson[0].name); // 用setState更新状态,触发组件重渲染 this.setState({ name: responseJson[0].name }) }) .catch(error => { console.log('error' +error); }); } render() { console.log('Start render ....'); console.log('Show view ...' ); console.log('this.state.name ...' + this.state.name); return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <Text>Hello, world ! {this.state.name}</Text> </View> ); } }
修复后逻辑:组件挂载后发起请求,请求成功后调用 setState 更新 name,React 检测到状态变化自动执行 render 方法,此时 this.state.name 已经是获取到的 Shyam,视图就会正常显示预期内容。
内容的提问来源于stack exchange,提问作者Desmond Ho
相关产品推荐
相关产品推荐

