2

Through the official documentation of antd we can know how to use the checkbox to complete the switch between multiple selection and single selection.

https://ant.design/components/checkbox/

My question is, if my checkbox data comes from a backend service, how should I maintain my data? It's accurate to say when I save the data in state of class so that the changes to the UI can be affected by changes in the data like the official documentation.

Now I try to traverse the back-end data when rendering the Dom, the following example code:

import { Checkbox } from 'antd';

const CheckboxGroup = Checkbox.Group;

class App extends React.Component {
  state = {
    indeterminate: true,
    checkAll: false,
  };

  render() {
    return (
      <div>
        <div style={{ borderBottom: '1px solid #E9E9E9' }}>
          <Checkbox
            indeterminate={this.state.indeterminate}
            onChange={this.onCheckAllChange}
            checked={this.state.checkAll}
          >
            Check all
          </Checkbox>
        </div>
        <br />
        {
          this.renderDomFunction(data) 
        }
      </div>
    );
  }
  // data is from back-end server
  renderDomFunction = (data) => {
    let plainOptions = []
    let defaultCheckedList = []
    let dom
    data.map(item => {
      plainOptions.push(
        { 
          label: <div>this is Orange</div>, 
          value: 'Orange', 
          disabled: false 
        },
        { 
          label: <div>this is Apple</div>, 
          value: 'Apple', 
          disabled: false 
        },
      )
      defaultCheckedList.push('Orange','Apple')
    })

    return (
      dom = <li>
        <CheckboxGroup
          options={plainOptions}
          value={defaultCheckedList}
          onChange={this.onChange}
        />
      </li>
    )
  }

  onChange = () => {
    // code...
    // I can't change the state of the checkbox by changing the data now, because isn't maintained in the state of Class.
  }
}

ReactDOM.render(<App />, mountNode);

I also tried to put the setstate() function into the renderDomFunction but this would cause an infinite loop.

Thank you!

vonfly
  • 71
  • 6
  • 1
    You can keep the value in your state, and inside `componentDidMount()` you can make your request to the back-end server, and update state. This means the initial state of the checkbox is empty, then updated from the backend server when the component is loaded through `componentDidMount()` then your `onChange` behaves as normal. – Carlos Reyes Aug 08 '19 at 14:27

0 Answers0