簡體   English   中英

ReactJS:是否可以在構造函數中獲取狀態值?

[英]ReactJS: Is it possible to get the state value in constructor?

有一個帶有輸入字段的組件。 輸入任何值會將其發送到狀態字段( searchString )。

現在,我需要將此狀態值放入我的構造函數中,因為它應該作為參數發送到我的訂閱中:

class Example extends Component {
    constructor(props) {
        super(props)
        const subscription = Meteor.subscribe('images', this.state.searchString) // <-- How to get state value?
        this.state = {
            ready       : subscription.ready(),
            subscription: subscription,
            searchString: ''
        }
    }

    searchImage(event) {
        const searchString = event.target.value
        this.setState({ searchString })
    }

    render() {
        const posts = Collection.find({}).fetch()
        return (<Input onChange={ this.searchImage.bind(this) }/>)
    }
}

export default Example

我試圖將值登錄到控制台,但是無法獲取狀態對象:

constructor(props) {
    super(props)
    console.log(this)       // I do get context, props, refs, state and updater objects
    console.log(this.state) // I do get `undefined`, but in the line above I do see state object with all fields
    const subscription = Meteor.subscribe('images')
    this.state = {
        ready       : subscription.ready(),
        subscription: subscription,
        searchString: ''
    }
}

構造函數在生命周期中僅被調用一次。 因此,一旦更新,狀態構造函數將不會被調用。

如果不進行突變,則不應將狀態存儲為狀態。 這也適用於將redux數據存儲到您的狀態。 不要重復數據。 Iam不知道訂閱是否異步,因此代碼設置應為其回調

不過不確定是否要訂閱一次? 根據代碼的邏輯,您正在訂閱搜索字段的每一次更改。 如果僅在第一次渲染時發生,請使用component(Did / Will)掛載周期

class Example extends Component {
    constructor(props) {
        super(props)
        this.state = {
            ready       : false,
            subscription: null,
            searchString: ''
        }
    }

    searchImage(event) {
        const searchString = event.target.value
        // Iam not sure, if subscribe is asynchronious so the code setting should be as its callback
        const subscription = Meteor.subscribe('images', searchString)
        this.setState({
          searchString,
          subscription,
          ready: subscription.ready();
        })
    }

    render() {
        const posts = Collection.find({}).fetch()
        return (<Input onChange={ this.searchImage.bind(this) }/>)
    }
}

export default Example

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM