axios请求数据传递后组件不重新渲染
创始人
2024-09-29 00:30:31
0
  1. 使用 shouldComponentUpdate 方法来检查组件是否需要重新渲染。在 shouldComponentUpdate 中比较新传递的数据和旧的数据,如果它们不相同,则返回 true,强制组件重新渲染。

例如:

class App extends React.Component { constructor(props) { super(props); this.state = { data: [] }; }

componentDidMount() { axios.get('api/data') .then(response => { this.setState({ data: response.data }); }) .catch(error => { console.log(error); }); }

shouldComponentUpdate(nextProps, nextState) { return this.state.data !== nextState.data; }

render() { return (

{this.state.data.map(item => (

{item.title}

))}
); } }

  1. 使用 componentDidUpdate 方法来检查数据是否发生变化。在 componentDidUpdate 中比较新传递的数据和旧的数据,如果它们不相同,则更新组件的状态,强制组件重新渲染。

例如:

class App extends React.Component { constructor(props) { super(props); this.state = { data: [] }; }

componentDidMount() { axios.get('api/data') .then(response => { this.setState({ data: response.data }); }) .catch(error => { console.log(error); }); }

componentDidUpdate(prevProps, prevState) { if (prevState.data !== this.state.data) { this.setState({ data: this.state.data }); } }

render() { return (

{this.state.data.map(item => (

{item.title}

))}
); } }

相关内容

热门资讯

透视推荐!aapoker透视怎... 透视推荐!aapoker透视怎么用(透视)智星德州插件2024最新版,教程法子(真的有挂)-哔哩哔哩...
透视普及!hhpoker透视码... 透视普及!hhpoker透视码(透视)aapoker公共底牌,教程模板(有挂规律)-哔哩哔哩1、上手...
透视揭露!hhpoker有没有... 透视揭露!hhpoker有没有开挂(透视)pokemmo辅助器手机版下载,教程步骤(有挂秘诀)-哔哩...
透视了解!hhpkoer辅助挂... 透视了解!hhpkoer辅助挂是真的吗(透视)哈糖大菠萝攻略,教程学习(证实有挂)-哔哩哔哩1、金币...
透视解迷!约局吧怎么看有没有挂... 透视解迷!约局吧怎么看有没有挂(透视)wepoker有没有机器人,教程窍门(确实有挂)-哔哩哔哩亲,...
透视推荐!wepokerplu... 透视推荐!wepokerplus透视脚本免费(透视)菠萝德州透视脚本,教程教材(存在有挂)-哔哩哔哩...
透视辅助!wepoker辅助器... 透视辅助!wepoker辅助器安装包(透视)wepoker插件程序激活码,教程阶段(有挂分析)-哔哩...
透视总结!wepoker安装教... 透视总结!wepoker安装教程(透视)约局吧开挂神器是真的吗,教程方式(有挂猫腻)-哔哩哔哩所有人...
透视详细!wepoker辅助器... 透视详细!wepoker辅助器安装包(透视)wepoker辅助器安装包,教程手筋(竟然有挂)-哔哩哔...
透视教你!wepoker透视有... 透视教你!wepoker透视有用吗(透视)智星菠萝透视,教程诀窍(有挂攻略)-哔哩哔哩1、首先打开w...