在没有使用react-redux前,我定义一个对象state1
,然后通过按钮点击,试图修改此对象里的属性值another
。
import React, { Component } from 'react'
export default class tryCom extends Component {
componentDidMount() {
console.log("只渲染一次")
}
fun = () => {
console.log("渲染多次");
this.state1.another+=3;
console.log(this.state1.another);
// this.forceUpdate()
}
state1 = {
another:3
}
render() {
return (
<div>
<p>another:{this.state1.another}</p>
<button onClick={this.fun}>点击修改</button>
</div>
)
}
}
发现并未修改过来,为什么,因为页面只在初始时渲染过一次,后来就算数据改变,组件也未被重新渲染。
下面通过forceUpdate()这个方法强制刷新一下:
fun = () => {
console.log("渲染多次");
this.state1.another+=3;
console.log(this.state1.another);
this.forceUpdate()
}
就会发现,页面上的内容也跟着一起变化了,这样就达到了我们的目的:
但是我们也知道,forceUpdate()的原理是再次调用rander方法,但这种强制刷新的方法我们应该少用,影响性能。
一般需要数据动态改变时,我们通过react的状态state来管理,数据一旦改变,state可以自动进行一次渲染。
如果现在我不使用state,我用react-redux来管理状态呢?
其实React与Redux并没有什么直接的联系。Redux作为一个通用模块,主要还是用来处理应用中state的变更,而展示层不一定是React。
但当我们希望在React+Redux的项目中将两者结合的更好,可以通过react-redux做连接。
参考:react-redux原理分析:https://www.cnblogs.com/hhhyaaon/p/5863408.html
如果只是单独使用redux,我们还要通过subscribe()方法来监听数据的变化,在store tree更新后反映到当前组件页面中来。不过react-redux将subscribe()内置了,不需要我们手动在组件内写监听就能实现页面的数据更改。
也就是说,react-redux也能重新渲染组件UI。
也就是说,在不进行强制刷新的情况下,上面案例的another值的改变也能体现在页面上。
我们从store中拿个值,并dispatch修改里面的某个数据,
import React, { Component } from 'react'
// dispatch分离出去的动作
import { ADD } from "../storenew/actionType.js"
// react-redux
import { connect } from "react-redux"
class tryCom extends Component {
componentDidMount() {
console.log("钩子componentDidMount---只执行一次")
}
fun = () => {
// console.log("渲染多次")
this.props.dispatch(ADD(4)) //dispatch方法发出的是异步 Action
console.log("store中的数据age:",this.props.stateParams.tryComReducer.age)
this.state1.another += 3;
console.log("another:",this.state1.another)
this.forceUpdate()
}
state1 = {
another: 3
}
render() {
console.log("render渲染",this.state1)
return (
<div>
<h4>I'm 尝试store的组件.</h4>
<p>another:{this.state1.another}</p>
<p>从store拿到的年龄:{this.props.stateParams.tryComReducer.age}</p>
<button onClick={this.fun}>点击修改</button>
</div>
)
}
}
export default connect(stateParams => ({ stateParams }))(tryCom)
dispatch方法发出的是异步 Action,这次的动作 ADD(4) 功能是每次给 age+4。
会发现,在改变store中age后,another也在页面重新渲染时跟着一起重新展示了。
总结
其实,不只react-redux会影响页面重新渲染,还有redux使用subscribe()方法时(react-redux内置了subscribe()),还有react中的状态state,在有数据改变后,同样会导致组件页面的重新渲染。
也就是说,如果页面重新渲染了,不管是自动的,还是强制的,我们都可以完成一些顺带操作。