我可以从componentDidMount调用onChange事件吗

时间:2019-11-14 14:17:46

标签: reactjs

在我的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。正确的方法是什么?

2 个答案:

答案 0 :(得分:2)

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

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>
    );
}

答案 1 :(得分:0)

很难看到我们可以看到的部分代码。 但是IMO,我们正在尝试做类似的事情

const updateValue = (value) => {
    // your code to manipulate this value;
    // this code was before in `handleChange`
    // like:

    this.setState({value: event.target.value});
}


handleChange = (event) => {
    const value = event.target.value;
    updateValue(value);
}

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