【问题标题】:How to update my selected options in the multiselect?如何更新我在多选中选择的选项?
【发布时间】:2019-12-29 16:48:28
【问题描述】:

我有一个选择,它显示了我从 api 检索到的一系列数据。 初始化时,它会显示已选择的选项卡,这很好。问题是当尝试选择更多选项或删除那些选项时,什么都没有发生。


import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

// Externals
import classNames from 'classnames';
import PropTypes from 'prop-types';
import compose from 'recompose/compose';
import validate from 'validate.js';
import _ from 'underscore';

// Material helpers
import { withStyles } from '@material-ui/core';

import moment from 'moment';

import 'bootstrap/dist/css/bootstrap.min.css';

import Select from 'react-select';

// Material components
import {
  Button,
  Checkbox,
  Grid,
  TextField,
  Typography
} from '@material-ui/core';

// Shared utilities
import validators from 'common/validators';
// Shared components
import {
  Portlet,
  PortletContent,
  PortletFooter
} from 'components';

// Component styles
import styles from './styles';

// Form validation schema
import schema from './schema';


class UserDetails extends Component {


  constructor (props) {
    super(props)

    this.state = {
      offices: [],
      officesSelected: [],

      isValid: false,
      isLoading: false,
      submitError: null
  };

    fetch(global.url_base+'/office' , {
      method: 'POST',
      body: JSON.stringify({ 
        id_user: this.props.location.id_user
      }),
      headers: {
              "Content-type": "application/json; charset=UTF-8"
      }
    })
    .then(response => response.json())
    .then(responseJson => {
      let langString = responseJson;
      let officesSelected = langString.map(item => ({ value: item.id_office, label: item.name_office, image: item.logo_office }));
      this.setState({
        officesSelected
      });
    }).catch(error => {
      console.error(error);
    });

  }

  componentWillMount() {
      let currentComponent = this;

      url = global.url_base+'/office'  
      fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        let langString = responseJson;

        let offices = langString.map(item => ({ value: item.id_office, label: item.name_office }));

        currentComponent.setState({
          offices
        });
      }).catch(error => {
        console.error(error);
      });
  }

  handleChangeMultiple = (event) => {

    const value = [];
    for (let i = 0, l = event.length; i < l; i += 1) {
        value.push(event[i].value);
    }
    const newState = { ...this.state };
    var field = 'id_office';
    newState.submitError = null;
    newState.touched[field] = true;
    newState.values[field] = value;
    this.setState(newState, this.validateForm);

  }

  render() {

    const { classes, className, ...rest } = this.props;
    const {
      values,
      touched,
      errors,
      isValid,
      submitError,
      offices,
      officesSelected
    } = this.state;

    const rootClassName = classNames(classes.root, className);

    return (

        <Select 
            className={classes.textField}
            styles={selectStyles}
            label="Office"
            name="id_office"
            onChange={this.handleChangeMultiple}
            options={offices}
            value={officesSelected}
            isMulti 
        /> 

如果我删除函数“value={officesSelected}”,我可以毫无问题地更改和添加多选选项卡,但我无法从 api 恢复已选择的选项卡数据。它总是显示好像我没有选择任何选项卡。

【问题讨论】:

  • 嗨 Vortex,您似乎使用的是 react-select 而不是 material-ui select,正如问题标签所暗示的那样。此外,您提供的代码还不够。我看不到officeSelected 值何时发生变化。请提供更多代码,最好是 Codesandbox 上的工作示例
  • 感谢您的回答。在这里我尽可能简洁地编辑了我的代码,我删除了几个不必要的部分。

标签: reactjs react-native jsx


【解决方案1】:

主要问题是这一行:

value={officesSelected}

officesSelected 仅在您的构造函数中更改。
在组件挂载之前(并且只要它仍然挂载),您的构造函数只会被调用一次。
这意味着,您的选择值将在构造函数中确定,并且在组件生命周期中不会更改。
为了实现你想要的,你需要在handleChangeMultiple中设置officesSelected的状态。
比如:

handleChangeMultiple = (event) => {

    const value = [];
    for (let i = 0, l = event.length; i < l; i += 1) {
        value.push(event[i].value);
    }
    const newState = { ...this.state };
    var field = 'id_office';
    newState.submitError = null;
    newState.touched[field] = true;
    newState.values[field] = value;
    newState.officesSelected = event; // I only added this line
    this.setState(newState, this.validateForm);

}

这应该使您能够选择更多选项并删除已选择的选项。


顺便说一句 - 在构造函数中调用 api 并不是最佳实践。
您应该在 ComponentDidMount 中进行 api 调用:https://reactjs.org/docs/react-component.html#componentdidmount

【讨论】:

  • 非常感谢!有用!事实上,我是 React 的新手,这是我的第一个应用程序,我也很感谢你的建议。
猜你喜欢
  • 1970-01-01
  • 2021-10-26
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多