gpt4 book ai didi

reactjs - react - componentWillReceiveProps 未运行

转载 作者:行者123 更新时间:2023-12-03 13:45:50 24 4
gpt4 key购买 nike

所以我是 react 新手,想知道如何创建一个传递一些参数的页面并根据这些参数获取文档。但是,当我尝试使用 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>
)
}
}

是因为我试图在其中有任何内容之前渲染状态吗?感觉就像我......这至少是我的猜测,正如文档所述,我得到了一个空对象。

最佳答案

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

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

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

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

<小时/>

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

componentWillReceiveProps :

componentWillReceiveProps() is invoked before a mounted component receives new props. React doesn't call componentWillReceiveProps with initial props during mounting. It only calls this method if some of component's props may update.

componentDidMount :

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

这样写:

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

关于reactjs - react - componentWillReceiveProps 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45901625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com