React - componentWillReceiveProps未运行

4

我是新手,想知道如何创建一个页面,可以传递几个参数并根据这些参数获取文档。但是,当我尝试使用componentWillReceiveProps时,发现它不运行,而且我不知道为什么。所以,能否有人用最简单的语言解释一下componentWillReceiveProps是什么,何时运行及其目的?我花了很多时间阅读react页面,但对于我来说,所有内容都像是一种全新的语言,因为我最近才开始学习react。您能否编辑下面的代码,使其可用,并让我自己看到它如何与其他内容一起工作(当我亲自看到它时,有助于我更好地理解)。

以下是我的页面代码:

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>
    )
  }
}

是因为我尝试在状态中还没有任何内容时就渲染状态吗?感觉好像是这样...至少我猜测我会得到一个空对象作为文档状态。


你有收到任何错误吗? - Edgar Henriquez
如果您的状态在开始时为空,那么测试componentWillReceiveProps方法的工作方式无关紧要吗? - Arnold Gandarillas
@EdgarHenriquez 没有错误,只是一个空白屏幕 - Stuart Fong
1个回答

3

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

1- 挂载方法:(仅在组件生命周期中调用一次)

2- 更新方法:(每当组件中发生任何更新时都会调用)

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


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

componentWillReceiveProps

componentWillReceiveProps() 在挂载的组件接收到新的 props 之前被调用。React 不会在挂载期间使用初始 props 调用 componentWillReceiveProps。仅在组件的某些 props 可能更新时才调用此方法。

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>
    )
  }
}

我没有遇到问题,但是我收到了一个警告,内容如下:“警告:setState(...):只能更新已挂载或正在挂载的组件。这通常意味着您在未挂载的组件上调用了setState()。这是无操作的。请检查fullSize组件的代码。” - Stuart Fong
你能展示一下你正在使用的完整组件(已更新)吗?你是在componentWillMount或componentWillUnmount方法中使用setState吗? - Mayank Shukla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接