为了账号安全,请及时绑定邮箱和手机立即绑定

反应选择默认值

反应选择默认值

当我将道具传递给它时,我有一个默认值为 null 的选择菜单,它会重新渲染新道具作为默认值这是我的选择组件:import React, { useState, useEffect } from "react"; import Select from "react-select"; class SelectMenu extends React.Component { state = {  defaultValues: [],  }; componentWillReceiveProps(newProps) {  this.setState({ defaultValues: newProps.defaultValue });  }  render() { return (  <Select    options={this.props.options}    closeMenuOnSelect={this.props.closeMenuOnSelect}    components={this.props.components}    isMulti={this.props.isMulti}    onChange={(e) => this.props.onChange(e, this.props.nameOnState)}    placeholder={this.props.default}    defaultValue={this.state.defaultValues}  />  ); }   } export default SelectMenu;
查看完整描述

3 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

我找到了解决这个问题的方法,方法是使用组件将接收道具并使用即将到来的道具设置我的状态,并且在渲染中你需要做条件来渲染选择菜单只有当 state.length !== 0

我发布了这个答案以防万一有人遇到同样的问题我知道它不是最佳解决方案但它对我有用


查看完整回答
反对 回复 2023-01-06
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

componentWillReceiveProps在安装期间不会被调用。


React 在安装期间不会使用初始道具调用 UNSAFE_componentWillReceiveProps()。如果某些组件的道具可能会更新,它只会调用此方法。( https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops )


此外,componentWillReceiveProps已弃用并将在 React 17 中删除。getDerivedStateFromProps改为查看,尤其是关于何时不需要它的注释。


我相信在您的情况下使用构造函数会非常好,例如:


class Components extends React.Component {

   constructor(props) {

      super(props)

      this.state = { some_property: props.defaultValue }

   }

}



查看完整回答
反对 回复 2023-01-06
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

对之前的解决方案感到抱歉,但它不是最佳的我找到了一种方法让它工作所以你必须将它作为值道具而不是默认值,如果你想将删除和添加的值捕获到你的默认值这个函数将帮助你很多


      onChange = (e) => {

   if (e === null) {

   e = [];

    }

     this.setState({

        equipments: e,

  });

  let added = e.filter((elm) => !this.state.equipments.includes(elm));

  if (added[0]) {

  let data = this.state.deletedEquipments.filter(

    (elm) => elm !== added[0].label

  );

   this.setState({

    deletedEquipments: data,

    });

  }


  let Equipments = e.map((elm) => elm.label);

  let newEquipments = Equipments.filter(

    (elm) => !this.state.fixed.includes(elm)

  );

  this.setState({

   newEquipments: newEquipments,

  });


   let difference = this.state.equipments.filter((elm) => !e.includes(elm));

   if (difference.length !== 0) {

   if (

     !this.state.deletedEquipments.includes(difference[0].label) &&

     this.state.fixed.includes(difference[0].label)

     ) {

     this.setState({

         deletedEquipments: [

         ...this.state.deletedEquipments,

           difference[0].label,

         ],

        });

      }

     }



    };


  constructor(props) {

   super(props);

   this.state = {

    equipments: [],

    newEquipments: [],

   deletedEquipments: [],

  };

 }


查看完整回答
反对 回复 2023-01-06
  • 3 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信