react小知识(1) - 这个defaultProps能够删掉吗?

初衷

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

实际业务中,因为组件render方法中,直接使用了list.map, 因此当listundefined, 会致使程序报错。ios

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

那么当redux来袭,这个defaultProps能够删掉吗?axios

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 this.props.list.map((item) => <span>{item.name}</span>);
  }
}

App.defaultProps = {
  list: []
};

export default App
复制代码

调查

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

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

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

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

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

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

    第二个连接里面提到了: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

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

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

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

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

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

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

此时,我已经完全的放心,在维护好 reducer 中的 initialState 的前提下,能够把项目中的 defaultProps 删掉了。

总结

  • 面对不肯定的代码,最好的态度并非放着无论,而是积极面对。也许他并不会对程序的运行形成影响,可是会妨碍你对框架的理解。

  • 须要进一步理解,向组件传递了 props ,为何 defaultProps 中的相同键值就不生效了。

  • 任何一个小问题搞明白都会使你快乐。

2019,开心的研究,期待技术上的成长!

相关文章
相关标签/搜索