当前位置:网站首页>函数组件和类组件和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}
},
},
}
边栏推荐
猜你喜欢

2021-04-26QGIS3.10加载天地图影像(地图瓦片)的一种方法

EndNote User Guide

Practical skills: a key for image information in the Harbor, quick query image

electron 应用开发优秀实践

【MySQL】mysql因为字符集导致left join出现Using join buffer (Block Nested Loop)

mac 上安装Redis和配置
![[贴装专题] 视觉贴装平台与贴装流程介绍](/img/ec/870af3b56a487a5ca3a32a611234ff.png)
[贴装专题] 视觉贴装平台与贴装流程介绍

自定义类型:结构体,枚举,联合

文件操作

分类预测 | MATLAB实现CNN-LSTM(卷积长短期记忆神经网络)多特征分类预测
随机推荐
EndNoteX9 OR X 20 Guide
SQL Server查询优化
Source GBase database, oracle quote "ORA - 01000: beyond the shop open the cursor"
2. Thread creation
EndNote使用指南
字符串函数和内存函数
mysql简单安装
By asking where the variables are stored, the shepherd boy laughed and said to use pointers, Go lang1.18 introductory refining tutorial, from Bai Ding to Hongru, the use of go lang type pointers (Poin
基于信号量与环形队列实现读写异步缓存队列
基本运算符
Multi-threaded cases - timer
五个不同事物隔离级别,七个事物传播行为
basic operator
goproxy.io 证书过期
Browser error classification
Battery modeling, analysis and optimization (Matlab code implementation)
OSCS开源软件安全周报,一分钟了解本周开源软件安全大事
[ASM] Bytecode operation MethodVisitor case combat generation object
pycharm在创建py文件时如何自动注释
函数二