当前位置:网站首页>函数组件和类组件和dva视图更新问题
函数组件和类组件和dva视图更新问题
2022-08-09 10:03:00 【高桥靓仔】
类组件setState视图更新:
import React from 'react'
export default class ThisSetState extends React.Component {
state = {
num: 1
}
render() {
return <div onClick={() => {
this.setState(() => {
this.state.num = 2
return this.state//新地址的state
})
}}>{this.state.num}</div>
}
}
this.setState的传入的状态是引用变量的话,地址和之前的不一样react才能正常触发更新,但是由于this的不确定性(因为this是调用的时候才确定)这里的this指向新的state,所以也会触发更新。
函数组件setState视图更新:
import React, { Component, useState } from 'react'
const ThisSetState = () => {
const [state, setState] = useState({ num: 1 })
return (
<div onClick={() => {
setState(() => {
state.num = 2
return state//直接返回的值地址渲染前和渲染后地址没有改变
})
}}>{state.num}</div>
)
}
export default ThisSetState
此时setState返回的值地址没有改变,所以点击时不会重新渲染。它类似 class 组件的 this.setState()
,但是它不会把新的 state 和旧的 state 进行合并(然而,不像 class 中的 this.setState
,更新 state 变量总是替换它而不是合并它。)
如果我们想要触发视图更新需要拷贝一下返回值:
import React, { Component, useState } from 'react'
const ThisSetState = () => {
const [state, setState] = useState({ num: 1 })
return (
<div onClick={() => {
setState(() => {
state.num = 2
return {...state}//新地址的变量
})
}}>{state.num}</div>
)
}
export default ThisSetState
redux通过props视图更新:
redux中是通过dispatch来触发model层数据改变,然后props传入组件来使视图更新,props也是需要视图更新前后引用变量地址发生变化,才重新渲染视图。
export default {
namespace: 'testModel',//单一状态树上的唯一标识(每一个model必须有唯一命名空间)
state: {
name: 'rayhomie'
},
reducers: {
setName(state, payload) {
console.log(payload);
// const _state = JSON.parse(JSON.stringify(state));
//state改变前后内存地址改变才能触发更新
// _state.name = payload.data.name
return {
...state}
},
},
}
边栏推荐
- OSCS开源软件安全周报,一分钟了解本周开源软件安全大事
- markdown转ipynb--利用包notedown
- 1. The concept of flow
- 【MySQL】mysql因为字符集导致left join出现Using join buffer (Block Nested Loop)
- day16_03集合
- 面试官:MySQL 中 update 更新,数据与原数据相同时会执行吗?大部分人答不上来!
- 3D打印了这个杜邦线理线神器,从此桌面再也不乱了
- 超详细的MySQL基本操作
- 分类预测 | MATLAB实现CNN-LSTM(卷积长短期记忆神经网络)多特征分类预测
- Attentional Feature Fusion
猜你喜欢
随机推荐
公里周日
缓存击穿,缓存穿透,缓存雪崩的解释和对应的一些解决方案
图表示学习(Graph Representation Learning)笔记
Technology Sharing | How to simulate real usage scenarios?mock technology to help you
What is the reason for the suspended animation of the migration tool in the GBase database?
《刷题日记》2
喜迎排名18
Sweet alert
markdown转ipynb--利用包notedown
Demand side power load forecasting (Matlab code implementation)
自定义类型:结构体,枚举,联合
3. Practice the Thread
MySQL关于表的知识点,进来学习!
class object property method class member
ORA-00600 [16703], [1403], [20]问题分析及恢复
cannot import name ‘load_offloaded_weights‘ from ‘accelerate.utils‘ (/home/huhao/anaconda3/envs/huha
Redis + NodeJS 实现一个能处理海量数据的异步任务队列系统
Throwing a question? The execution speed of the Count operation in the Mysql environment is very slow. You need to manually add an index to the primary key---MySql optimization 001
收到人生第一笔五位数工资
主从postition变化无法锁定_Slave_IO_Running显示No_Slave_Sql_Running显示No---Mysql主从复制同步002