2017-08-27 55 views
2

所以我是新來的反應,想知道如何創建一個頁面,傳遞幾個參數,並根據這些參數獲取文檔。但是,當我嘗試使用componentWillReceiveProps時,發現它不運行,我不知道爲什麼。那麼是否有人可以用最簡單的術語解釋什麼是componentWillReceiveProps,它何時運行及其目的?我花了好幾個小時試圖閱讀反應頁面,但對我來說,它似乎是一種全新的語言,因爲我最近纔開始反應。你還可以編輯下面的代碼,以便它能夠工作,並且我可以看到它與其他內容一起工作的方式(當我自己看到它時,它可以幫助我更好地理解)。react - componentWillReceiveProps not running

下面是我的網頁代碼:因爲我想呈現狀態之前在它裏面什麼

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

是什麼呢?感覺就像我......這就是我的猜測,至少我得到一個空的對象作爲文檔狀態。

+0

你得到任何錯誤? –

+0

開始時你的狀態是否爲空並不重要,你如何測試'componentWillReceiveProps'方法是否工作? –

+0

@EdgarHenriquez沒有錯誤只是一個空白的屏幕 –

回答

0

基本概念是,我們有這些類型的生命週期方法:

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

我不明白,但我得到一個警告說,「警告:setState(...):只能更新已安裝或已安裝的組件。這通常意味着您在卸載的組件上調用了setState()。這是一個沒有操作。請檢查fullSize組件的代碼。「 –

+0

可以顯示完整組件(更新)是否使用componentWillMount或componentWillUnmount方法中的setState? –

+0

小錯誤在我身邊,謝謝所有已修復 –