繁体   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