C
C
chelkaz2018-10-30 18:25:45
React
chelkaz, 2018-10-30 18:25:45

React how to outsource getting Axios data to a class?

Now I have the following scheme:
First, const variables
Here is an example of my code https://codepen.io/anon/pen/QZRGjM
In it, the data is taken from the gData
variable But I plan to pull the data with a request from Axios

componentDidMount() {
        axios
            .get('/list')
            .then(response => {
                this.setState({
                    treeData: response.data,
                });
                console.log(response);
            })
            .catch(error => console.error(error));
    }

And in the class, instead of the gData variable, I specify There are this.state.treeData
three problems:
1) The search does not work after replacing gData with this.state.treeData
2) I have to specify it this way !this.state.treeData ? [] : this.state.treeDataBecause it renders faster than the data appears
3) The problem stops welding the tree until you close the child ones when gData is static, without axios then everything works.
Here is the complete example code. In which I need to correctly inject Axios and replace gData with the incoming json
const { Tree, Input } = antd;

const TreeNode = Tree.TreeNode;
const Search = Input.Search;
const gData = [
    {
        title: "Все товары 001", key: "0-0", children: [
            {title: "Первый подраздел 22", key: "0-1555", children: null},
            {title: "Еще подраздел 557", key: "0-2", children: null},
            {title: "Тоже подраздел 321", key: "0-3", children: [
                    {title: "Тут раздел 21232", key: "0-1535", children: null},
                    {title: "Подраздел 55117", key: "0-233", children: null},
                ]
            }
        ]
    }
];


const dataList = [];
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({ key, title: node.title });
    if (node.children) {
      generateList(node.children, node.key);
    }
  }
};
generateList(gData);

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

class SearchTree extends React.Component {
  state = {
    expandedKeys: [],
    searchValue: '',
    autoExpandParent: true,
  }

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }

  onChange = (e) => {
    const value = e.target.value;
    const expandedKeys = dataList.map((item) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, gData);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  }

  render() {
    const { searchValue, expandedKeys, autoExpandParent } = this.state;
    const loop = data => data.map((item) => {
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      const title = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.title}</span>;
      if (item.children) {
        return (
          <TreeNode key={item.key} title={title}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} title={title} />;
    });
    return (
      <div>
        <Search style={{ marginBottom: 8 }} placeholder="Поиск" onChange={this.onChange} />
        <Tree
          onExpand={this.onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
        >
          {loop(gData)}
        </Tree>
      </div>
    );
  }
}

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

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question