首页 > 解决方案 > 我可以从 componentDidMount 调用 onChange 事件吗

问题描述

在我的 React 应用程序中,我有以下代码:

...
handleChange(event) {

    let chunkedText = []
    this.setState({value: event.target.value});
    let text = event.target.value

   ...

    //store the text in local storage with the key 'tweet'
    window.localStorage.setItem('tweet', text);

   ...

  componentDidMount() {
    //once the component loads check local storage and update the value if it exists
    if(window.localStorage.getItem('tweet')) {
      this.setState({value: window.localStorage.getItem('tweet')});
    }
  }

  render() {
    return (
      <div>
        <form>
          <label>
            <textarea
              placeholder="Begin typing your tweet here..."
              rows="14" cols="50" value={this.state.value}
              onChange={this.handleChange}
            />
          </label>
        </form>
        {this.state.length > 0 ? <span>{this.state.length} Chars || {this.state.count} Tweets</span> : ''}
      </div>
    );
  }
}

请注意,在 componentDidMount 中,我们从本地存储中提取一些文本并设置状态。理想情况下,在此之后(在 componentDidMount 中)我想运行 handleChange。这样做的正确方法是什么?

标签: reactjs

解决方案


我会将代码更改为以下内容:

handleChange(event) {

    this.handleValue(event.target.value);
}

handleValue(value) {

    let chunkedText = []
    this.setState({ value: value });
    let text = value

    //...

    //store the text in local storage with the key 'tweet'
    window.localStorage.setItem('tweet', text);

    //...
}

componentDidMount() {
    //once the component loads check local storage and update the value if it exists
    if (window.localStorage.getItem('tweet')) {
        this.handleValue(window.localStorage.getItem('tweet'))
    }
}

render() {
    return (
        <div>
            <form>
                <label>
                    <textarea
                        placeholder="Begin typing your tweet here..."
                        rows="14" cols="50" value={this.state.value}
                        onChange={this.handleChange}
                    />
                </label>
            </form>
            {this.state.length > 0 ? <span>{this.state.length} Chars || {this.state.count} Tweets</span> : ''}
        </div>
    );
}

推荐阅读