美文网首页
将 state 赋值给 defaultValue

将 state 赋值给 defaultValue

作者: 杜朝辉 | 来源:发表于2019-11-20 16:18 被阅读0次

目的想把异步获取的一个数据 sourceId 经过加工 (isNet  = sourceId > 3 ? 1 : 0 ),通过 setState 赋值给 state 中的 isNet 字段;

刚开始的时候设置在 componentWillReceiveProps 生命周期中:

componentWillReceiveProps(nextProps: Readonly<CustomerFormProps>): void {

    const { CustomerEditService: { sourceId } } = nextProps;

    if (sourceId === this.props.CustomerEditService.sourceId) {

        return

    }

    this.setState({ isNet  :  sourceId > 3 ? 1 : 0 });

}

结果在 render 中设置 select 的 defaultValue 并没有产生效果:

经过查询文档将设置放在 componentWillMount 生命周期中,效果实现。

componentWillMount(): void {

    const { CustomerEditService: { sourceId } } = this.props;

    const isNet = sourceId > 3 ? 1 : 0;

    this.setState({ isNet });

}

<Col lg={6} md={24} style={{ paddingLeft: 0 }}>

    <Form.Item label={fieldLabels.channel}>

        {/* 是否网络客户选择 */}

        <Select defaultValue={ isNet } onChange={value => this.onSelectNet(value)}>

            { csr_src_type.son.map( (item, index) => <Option key={ item.id } value={ index }> { item.name } </Option>, ) }

        </Select>

    </Form.Item>

</Col>

相关文章

网友评论

      本文标题:将 state 赋值给 defaultValue

      本文链接:https://www.haomeiwen.com/subject/tkwoictx.html