React知识杂烩(持续更新)

每隔半年不看官方文档,你就会不认识React了😁

React组件生命周期

1.React 15.x

componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
componentDidUpdate(prevProps, prevState)

2.React 16.3
IMG_3146

  • static getDerivedStateFromProps是在render方法之前调用的, 组件初次加载和后续更新的时候都会调用,返回一个对象来更新state,如果返回null则不做任何更新.需要注意的是这个方法是静态方法,在方法内this不是指向组件实例的,this.props/this.state是取不到组件数据的
  • getSnapshotBeforeUpdate是在最近一次渲染更新到真实DOM节点之前被调用的,这个方法的返回值会作为第三个参数传入componentDidUpdate方法

React生命周期参考16.3+

受控组件与非受控组件

受控组件:表单数据由React组件控制(通过props或者state控制)

class Form extends Component {
  constructor() {
    super();
    this.state = {
      name: '',
    };
  }

  handleNameChange = (event) => {
    this.setState({ name: event.target.value });
  };

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.name}
          onChange={this.handleNameChange}
        />
      </div>
    );
  }
}

非受控组件:数据由真实的DOM控制(使用ref获取真实的DOM)

class Form extends Component {
  handleSubmitClick = () => {
    const name = this._name.value;
    // do something with `name`
  }

  render() {
    return (
      <div>
        <input type="text" defaultValue="Bob" ref={input => this._name = input} />
        <button onClick={this.handleSubmitClick}>Sign up</button>
      </div>
    );
  }
}

两种组件该如何选择

参考:Controlled and uncontrolled form inputs in React don't have to be complicated

多个输入的解决方法

当你有处理多个受控的input元素时,你可以通过给每个元素添加一个name属性,来让处理函数根据 event.target.name的值来选择做什么。

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

Props.children可以传递任何数据包括函数

// Calls the children callback numTimes to produce a repeated component
function Repeat(props) {
  let items = [];
  for (let i = 0; i < props.numTimes; i++) {
    items.push(props.children(i));
  }
  return <div>{items}</div>;
}

function ListOfTenThings() {
  return (
    <Repeat numTimes={10}>
      {(index) => <div key={index}>This is item {index} in the list</div>}
    </Repeat>
  );
}

布尔值、Null 和 Undefined 被忽略

false、null、undefined 和 true 都是有效的子代,但它们不会直接被渲染。下面的表达式是等价的:

<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>

值得注意的是,JavaScript 中的一些 “falsy” 值(比如数字0),它们依然会被渲染。例如,下面的代码不会像你预期的那样运行,因为当 props.message 为空数组时,它会打印0:

<div>
  {props.messages.length &&
    <MessageList messages={props.messages} />
  }
</div>

要解决这个问题,请确保 && 前面的表达式始终为布尔值:

<div>
  {props.messages.length > 0 &&
    <MessageList messages={props.messages} />
  }
</div>

相反,如果你想让类似 false、true、null 或 undefined 出现在输出中,你必须先把它转换成字符串 :

<div>
  My JavaScript variable is {String(myVariable)}.
</div>

使用 PropTypes 进行类型检查(直接参考官方文档)

react-redux中mapDispatchToProps方法无法访问Store中state,怎么办???

最近在开发过程中遇到这样一种场景:在mapDispatchToProps需要根据state中某个状态决定引入何种dispatchProps,但是mapDispatchToProps没有提供直接访问state的方式,
mapDispatchToProps可以是对象或者函数,当为函数时,其函数签名如下:mapDispatchToProps(dispatch, [ownProps]): dispatchProps,因此在mapDispatchToProps中并不能实现这种需求。但是借助connect方法的第三个参数mergeProps可以实现我们的需求
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

[mergeProps(stateProps, dispatchProps, ownProps): props] (Function): 如果指定了这个参数,mapStateToProps()mapDispatchToProps() 的执行结果和组件自身的 props 将传入到这个回调函数中。该回调函数返回的对象将作为 props 传递到被包装的组件中。你也许可以用这个回调函数,根据组件的 props 来筛选部分的 state 数据,或者把 props 中的某个特定变量与 action creator 绑定在一起。如果你省略这个参数,默认情况下返回 Object.assign({}, ownProps, stateProps, dispatchProps) 的结果。如果我们需要根据state中的状态决定dispatchProps,可以先在mapStateToProps()将其映射到stateProps中,然后在mergeProps中重新构造dispatchProps

Add state as the third parameter to mapDispatchToProps
Access state props in mapDispatchToProps

posted @ 2018-10-19 18:05  FeMiner  阅读(374)  评论(0编辑  收藏  举报