如何动态设置初始状态?

时间:2019-04-23 15:00:46

标签: reactjs

我的初始状态会有所不同,具体取决于我从API调用中获得的数量。

所以基本上有时候看起来像这样:

  class MyComponent extends Component {
    state = {
     activeItem0: '',
     activeItem1: '',
     activeItem2: '',
     activeItem3: '',
   } 
    ...

有时候,根据数据库返回的数据,它可能看起来像这样。

  class MyComponent extends Component {
    state = {
     activeItem0: '',
     activeItem1: '',
     activeItem2: '',
     activeItem3: '',
     activeItem4: '',
     activeItem5: '',
   } 
    ...

是否可以动态设置初始状态键?

这是我到目前为止的内容:

class MyComponent extends Component {
  state = {
   activeItem0: '',
   activeItem1: '',
   activeItem2: '',
   activeItem3: ''
 }

 // Set the value for each product on the store
  handleItemClick = (e, { name, children }) => this.setState({[e.target.name]: children })

 let buttonGroup = _.times(products.length, i => (
    <Button.Group>
       <Button
         name={`activeItem${i}`}
         active={this.state[`activeItem${i}`] === 'Val1'}
         onClick={this.handleItemClick}
        >
          Val1
       </Button>

       <Button
         name={`activeItem${i}`}
         active={this.state[`activeItem${i}`] === 'Val2'}
         onClick={this.handleItemClick}>
         Val2
        </Button>

        <Button
         name={`activeItem${i}`}
         active={this.state[`activeItem${i}`] === 'Val3'}
         onClick={this.handleItemClick}>
          Val3
        </Button>
      </Button.Group>
    )

 render() {
  return(
     <div>
       <Grid container>{selectSizeInSideBar}</Grid>
     </div>
    )
   }
  }

因此,问题在于,如果DatabBase返回的products.length4  我应该处于这样的初始状态

   state = {
    activeItem0: '',
    activeItem1: '',
    activeItem2: '',
    activeItem3: ''
   }

但是如果我的数据库products.length6,则 我的初始状态应如下所示:

   state = {
    activeItem0: '',
    activeItem1: '',
    activeItem2: '',
    activeItem3: ''
    activeItem4: ''
    activeItem5: ''
   } 

1 个答案:

答案 0 :(得分:0)

您可以创建一个在组件准备就绪后初始化状态的方法(假设您的API数据已收到),因此最好在componentDidMount中使用该方法。

const initializeStateForKeys = ( products ) => {
   const fakeState = {};
   _.each( products, product => {  
     fakeState[ product.id ] = { id: product.id ,isActive: product.isActive }
   } );

   return fakeState
}

,您应该这样使用它:

componentDidMount(){
  API.fetchMyProducts()
  .then( response => {
    this.setState( { products: response.data.products } 
    , () => {
     this.initializeStateForKeys( this.state.products);
    }); 
   });
}