react - componentWillReceiveProps未运行

时间:2017-08-27 04:13:07

标签: reactjs meteor

所以我是新手,我想知道如何创建一个传递几个参数并根据这些参数获取文档的页面。但是,当我尝试使用componentWillReceiveProps时,我发现它没有运行,我不知道为什么。那么有人可以用最简单的术语解释它们可以是什么componentWillReceiveProps,什么时候运行它的目的?我花了很多时间试着阅读反应页面,但由于我最近刚刚开始做出反应,所以这对我来说似乎是一种全新的语言。你也可以编辑下面的代码,这样它可以工作,我可以自己看看它是如何与其他东西一起工作的(当我亲眼看到它时,它有助于我更好地理解)。

以下是我的网页代码:

import React from "react";
import { Tracker } from "meteor/tracker";
import { Link } from "react-router-dom"

import Menu from "./Menu"
import { Notes } from "../methods/methods";

export default class fullSize extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      doc: {}
    };
  }
  componentwillMount() {
    Meteor.subscribe("notes");
  }
  componentWillReceiveProps(nextProps) {
    this.tracker = Tracker.autorun(() => {
      const doc = Notes.findOne(nextProps.match.params.noteId);
      this.setState({ doc })
    })
  }
  renderNote(){
    console.log(this.state.doc)
  }
  render(){
    return (
      <div>{this.renderNote()}</div>
    )
  }
}

是因为我试图在状态之前呈现状态吗?感觉就像我...这就是我的猜测,至少我得到一个空对象作为doc状态。

1 个答案:

答案 0 :(得分:2)

基本概念是我们有这些类型的生命周期方法:

1-安装方法:(仅对该组件的生命周期调用一次)

2-更新方法:(只要组件发生任何更新,就会调用)

3-卸载方法:(当组件将卸载时)

componentWillReceiveProps是一种更新方法,只有在道具值发生任何变化时才会运行,它不会在初始渲染时运行,因此您需要同时使用componentWillReceivePropscomponentDidMount方法。 componentDidMount将获取初始数据,如果该页面收到新道具,则componentWillReceiveProps将获取新数据。

componentWillReceiveProps

  

在安装的组件之前调用componentWillReceiveProps()   收到新的道具。 React不会调用componentWillReceiveProps   安装时的初始道具。如果有的话,它只会调用此方法   组件的道具可能会更新。

componentDidMount

  

componentDidMount()在组件出现后立即调用   安装。需要DOM节点的初始化应该放在这里。如果你   需要从远程端点加载数据,这是一个好地方   实例化网络请求。在这种方法中设置状态会   触发重新渲染。

像这样写:

export default class fullSize extends React.Component{

  constructor(props){
    super(props);
    this.state = {
      doc: {}
    };
  }

  componentwillMount() {
    Meteor.subscribe("notes");
  }

  componentDidMount() {
    this.tracker = Tracker.autorun(() => {
      const doc = Notes.findOne(this.props.match.params.noteId);
      this.setState({ doc })
    })
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.match.params.noteId != nextProps.match.params.noteId)
      this.tracker = Tracker.autorun(() => {
        const doc = Notes.findOne(nextProps.match.params.noteId);
        this.setState({ doc })
      })
  }

  renderNote(){
    console.log(this.state.doc)
  }

  render(){
    return (
      <div>{this.renderNote()}</div>
    )
  }
}
相关问题