1

Is it possible to create states in the constructor passed to that component from an array or object.

Here is what is to be achieved:

constructor(props) {
    super(props);
    this.state= {
        Object.keys(this.props.data).map((key, i) => {
            [key]: 'boo',
        })
    }
}

but it returns a syntax error.

The idea is that the data within this.props.data creates a series of states. The data passed to this.props.data is not known by the component in advance but is passed to it as a prop when the component is used.

1 Answer 1

2

You could directly declare this.state with return array of map

updated

constructor(props) {
    super(props);
    this.mapData = Object.keys(this.props.data).map((key, i) =>({[key]: 'boo'}))
    this.state = this.pre_state ? Object.assign({}, ...this.pre_state) : {};
}
Sign up to request clarification or add additional context in comments.

2 Comments

However, the state is not accessible. Calling this.state.WhateverTheKeyWas returns as undefined.
Sorry . this.state only accept as object . i just updated my answer .You could use Object.assign for creating array to object .sample eg codesandbox.io/s/staging-cdn-pr6td

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.