react.children.map:当状态多次改变时,元素被重新渲染

时间:2018-08-03 08:11:57

标签: javascript reactjs react-native

enter image description here

故事书中已经写了三个单选按钮。这些元素已从故事书中作为道具发送。

故事书

storiesOf("Form", module)
.add("RadioGroup", () => (
  <Form>
    <RadioGroup
      id={text('id', 'group_unique_id')}
      name={text('name', 'should_same_group')}
      value={text('value', '1')}
      block={boolean('block',false)}
      disabled={boolean('disabled',false)}
      className={text('className', '')}
      onChange={action('changed')}
    >
      <Radio
        label='Radio Button 1'
        name='should_same'
        value='1'
      />
      <Radio
        label='Radio Button 2'
        name='should_same'
        value='2'
      />
      <Radio
        label='Radio Button 3'
        name='should_same'
        value='3'
      />
    </RadioGroup>
  </Form>
)
)

作为道具发送到故事书的组件由render方法渲染。所有道具均通过render方法进行映射,如果存在子代,则将其克隆。到目前为止看起来还可以。

render () {
    const {children} = this.props

    return (
      <View id={this.props.id}>
      {

        React.Children.map(children, (child, index) => {
          if (child) {
            console.log(`${child.props.value} rendered`)
            return React.cloneElement(child, {
              id: 'radio_' + index + '_' + child.props.name,
              name: child.props.name,
              disabled: this.props.disabled,
              checked: child.props.value == this.state.value,
              onChange: this.onChange.bind(this, index)
            })
          }
        })
      }

      </View>
    )
  }
}

调用单选按钮click方法并发生状态更改时,它不会瞄准元素并且不会部分呈现它。取而代之的是,它渲染所有元素,并且每个元素都克隆三遍。我调试了代码,然后意识到它遍历了每个单个元素,并且正在克隆每个子元素。这意味着最后一次重新渲染,而克隆的元素始终是第三个元素。

生命周期和方法

 componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      this.setState({
        value: nextProps.value
      })
    }
  }

  onChange (child) {
    if (this.props.onChange) {
      const allChilds = this.props.children
      allChilds.map((v, i) => {
        if(i === child){
          let activeChildValue = v.props.value
          if(typeof activeChildValue === "string") { 
            this.setState({value:activeChildValue})
            break
          }
        }
      })
    }
  }

任何建议将不胜感激。

0 个答案:

没有答案
相关问题