react小知识(1) - 这个defaultProps可以删掉吗?

栏目: 服务器 · 发布时间: 7年前

内容简介:业务代码在实际业务中,由于组件因此,在开发第一个

业务代码在 react 组件向 react-redux 模式转换中,出现了一段不确定是否冗余的代码

实际业务中,由于组件 render 方法中,直接使用了 list.map , 所以当 listundefined , 会导致程序报错。

因此,在开发第一个 react 版本时,对 App.defaultProps 进行了定义。这段代码对保障程序的可用性,有重要的意义。

那么当 redux 来袭,这个 defaultProps 可以删掉吗?

import React , { Component } from 'react';
import { connect } from "react-redux";

@connect(
  state => ({
    // 已在appReducer中定义list的初值为[]
    list: state.appReducer.list 
  })
)
class App extends Component {
  
  componentDidMount() {
    // react写法, 此处略去axios声明
    axios.get('http://api.xxx.com').then((response) => {
      this.setState({
        list: response.data.list
      })
    })
    
    // redux写法, 此处略去requestList声明
    // 依赖action -> reducer -> mapStateToProps 更新list
    // axios请求通常写在action中,需使用 redux-thunk 中间件
    // this.props.requestList();
  }

  render() {
    return list.map((item) => <span>{item.name}</span>);
  }
}

App.defaultProps = {
  list: []
};

export default App
复制代码

调查

  1. google 检索,关键词: mapStateToProps defaultProps

    搜索引擎返回的结果,对我理解此问题有帮助的,有以下2个链接。

    1. set-default-props-for-a-react-component

    2. how-to-declare-reactjs-default-props-when-using-redux

    第一个链接里面提到了:As mapStateToProps is being called before the component construction (when defaultProps are defined)

    mapStateToProps 是在组件的contructor前调用的。

    第二个链接里面提到了:after you shared your mapStateToProps , yes, it has something to do with Redux ! The issue is caused by your reducer.

    You must declare initial state shape and moreover, you must specify the initial state in each reducer.

    Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app.

    Redux 会使用一个 undefined 状态对 reducer 进行调用,此时,我们可以返回 app 的初始状态

  2. 安装一个 react-redux 脚手架进行实践,本次选了 react-redux-boilerplate

    react小知识(1) - 这个defaultProps可以删掉吗?

    如图所示, defaultProps 中的 username 并没有生效。

    而且在 HomePage 组件的 constructor 方法中,打印出来的日志中, username 也是 reducer initial state 赋予的值。

    react小知识(1) - 这个defaultProps可以删掉吗?

    还有一张图,更好的说明了这个问题,其实被 connect 包裹的 HomePage 组件,实际的调用情况就是

    <HomePage username="fengyu" />
    复制代码

    这和我们直接使用 react 组件时,传递了 props , 组件内的 defaultProps ,就不会生效的道理是一摸一样的。

    同样对上面检索结果中提到的, mapStateToProps 是在组件的contructor前调用,做了很好的印证。

此时,我已经彻底的放心,在维护好 reducer 中的 initialState 的前提下,可以把项目中的 defaultProps 删掉了。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

并行计算导论

并行计算导论

Ananth Grama、George Karypis、张武、毛国勇、Anshul Gupta、Vipin Kumar、程海英 / 张武、毛国勇、程海英 / 机械工业出版社 / 2005-1-1 / 49.00元

《并行计算导论》(原书第2版)全面介绍并行计算的各个方面,包括体系结构、编程范例、算法与应用和标准等,涉及并行计算的新技术,也覆盖了较传统的算法,如排序、搜索、图和动态编程等。《并行计算导论》(原书第2版)尽可能采用与底层平台无关的体系结构并且针对抽象模型来设计处落地。书中选择MPI、POSIX线程和OpenMP作为编程模型,并在不同例子中反映了并行计算的不断变化的应用组合。一起来看看 《并行计算导论》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具