博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
当属性更改时重新渲染React组件
阅读量:2537 次
发布时间:2019-05-11

本文共 2174 字,大约阅读时间需要 7 分钟。

Imagine you have a React and Redux project with two components, a parent and a child.

假设您有一个具有两个组件的React和Redux项目,一个父级和一个子级。

The parent component passes some props to the child component. When the child component receives those props, it should call some Redux action which changes some of the props that were passed from the parent asynchronously.

父组件将一些道具传递给子组件。 当子组件接收到这些道具时,它应该调用Redux操作,该操作会更改从父级异步传递的一些道具。

Here are the two components:

这是两个组件:

父组件 (Parent Component)

class Parent extends React.Component {  getChilds(){    let child = [];    let i = 0;    for (let keys in this.props.home.data) {      child[i] = (        
); i++; if (i === 6) break; } return Rows; } render(){return (

I am gonna call my child

{this.getChilds()}
)

子组件 (Child Component)

class Child extends React.Component { componentDidMount(){  if(this.props.data.items.length === 0){    // calling an action to fill this.props.data.items array with data   this.props.getData(this.props.data.id);  } }  getGrandSon(){  let grandSons = [];  if(this.props.data.items.length > 0){   grandSons = this.props.data.items.map( item => 
); } return grandSons; } render(){ return (

I am the child component and I will call my own child

{this.getGrandSon()}
) }}

The redux-store is updated properly, but the child component doesn't re-render.

redux-store已正确更新,但子组件未重新呈现。

It's normally not the responsibility of the Child to fill the data. Instead, it should receive data that's already been prepared by the Parent. Also, props are automatically updated.

填写数据通常不是Child的责任。 相反,它应该接收Parent已经准备好的数据。 此外,道具会自动更新。

Still, it can be useful to update and manipulate data from a Child component, especially when Redux is involved.

尽管如此,更新和处理Child组件中的数据仍然很有用,尤其是在涉及Redux时。

React is probably performs shallow comparisons, and might not re-render even though the state is clearly changing.

React可能会执行浅层比较,即使状态明显改变,它也可能不会重新呈现。

As a workaround, you can do this in mapStateToProps:

解决方法是,可以在mapStateToProps执行以下mapStateToProps

const mapStateToProps = state => {  return {     id: state.data.id,   items: state.data.items  }}

翻译自:

转载地址:http://vtzzd.baihongyu.com/

你可能感兴趣的文章
9_2二维数组
查看>>
为django项目创建虚拟环境
查看>>
30-RoutingMiddleware介绍以及MVC引入
查看>>
【转】AB实验设计思路及实验落地
查看>>
PHP获取客户端的IP
查看>>
C# 创建单例窗体封装
查看>>
移动端报表如何获取当前地理位置
查看>>
spring 源码
查看>>
使用 opencv 将图片压缩到指定文件尺寸
查看>>
linux中~和/的区别
查看>>
在vue-cli项目中使用bootstrap的方法示例
查看>>
jmeter的元件作用域与执行顺序
查看>>
echarts学习笔记 01
查看>>
PrimeNG安装使用
查看>>
iOS 打包
查看>>
.NET Core中的数据保护组件
查看>>
华为云软件开发云:容器DevOps,原来如此简单!
查看>>
MyEclipse 快捷键(转载)
查看>>
03链栈_LinkStack--(栈与队列)
查看>>
会滚段
查看>>