【问题标题】:ReactJs: set initial state using props while using dynamic TaglistReactJs:在使用动态 Taglist 时使用道具设置初始状态
【发布时间】:2017-11-27 07:45:10
【问题描述】:

我正在发送一个名为 tags 的数组作为道具,我想将其分配为初始状态,以便显示这些数组元素。使用此代码它们可以正确显示,但我无法编辑它们。当我单击交叉时,它会被删除,但一段时间后它会再次显示。似乎 handelClose 方法中的 setState 不起作用。

import React from 'react';
import ReactDOM from 'react-dom';
import { Tag, Input, Tooltip, Button } from 'antd';

class EditableTagGroup extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tags: [],
      inputVisible: false,
      inputValue: '',
    };
  }

  handleClose = (removedTag) => {
    // debugger;
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    console.log(tags);
    // debugger;
    this.setState({ tags: tags });
  }

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  }

  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  }

  handleInputConfirm = () => {
    const state = this.state;
    const inputValue = state.inputValue;
    let tags = state.tags;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue];
    }
    console.log(tags);
    this.setState({
      tags,
      inputVisible: false,
      inputValue: '',
    });
    this.props.onSelect(tags);
  }

  // componentDidUpdate(prevProps, prevState) {
  //   this.setState({tags: this.props.tags})
  // }

  componentDidUpdate(prevProps, prevState) {
    // debugger;
    if (this.state.tags  !== this.props.tags) {
      this.setState({tags: this.props.tags})
    }
  }

  saveInputRef = input => this.input = input

  render() {
    const {tags , inputVisible, inputValue } = this.state;
    return (
      <div>
        {tags.map((tag, index) => {
          const isLongTag = tag.length > 20;
          const tagElem = (
            <Tag key={tag} closable={index !== -1} afterClose={() => this.handleClose(tag)}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </Tag>
          );
          return isLongTag ? <Tooltip title={tag} key={tag}>{tagElem}</Tooltip> : tagElem;
        })}
        {inputVisible && (
          <Input
            ref={this.saveInputRef}
            type="text"
            size="small"
            style={{ width: 78 }}
            value={inputValue}
            onChange={this.handleInputChange}
            onBlur={this.handleInputConfirm}
            onPressEnter={this.handleInputConfirm}
          />
        )}
        {!inputVisible && <Button size="small" type="dashed" onClick={this.showInput}>+ New Tag</Button>}
      </div>
    );
  }
}

export default EditableTagGroup

【问题讨论】:

  • 它会更新,因为当新的道具进来时......它通过componentDidUpdate更新为状态。因此,您应该放置一些逻辑来确定更新到状态的内容。
  • 尝试不使用componentDidUpdate 处理程序。也许你想要componentWillReceiveProps

标签: reactjs taglist


【解决方案1】:

问题在于,您在本地状态下保存和使用道具,然后修改它们,但是每次组件更新时,您都将状态设置回道具。

// this is where you are setting the state back to 
// props and hence your edit disappears
componentDidUpdate(prevProps, prevState) {
    // debugger;
    if (this.state.tags  !== this.props.tags) {
      this.setState({tags: this.props.tags})
    }
  }

您需要做的不是维护状态中的道具,而是直接修改它,通过从父级传递处理程序来更新道具。

请参阅此答案以了解如何在父级中传递和更新数据

How to pass data from child component to its parent in ReactJS?

【讨论】:

  • 绝对!此外,如果 tags 是一个集合,则此差异检查将始终返回 true。
  • 非常感谢。
猜你喜欢
  • 2018-03-20
  • 2019-11-11
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 2018-06-10
  • 2019-09-20
  • 2017-10-02
  • 1970-01-01
相关资源
最近更新 更多