【问题标题】:How to maintain state如何保持状态
【发布时间】:2019-08-23 18:38:41
【问题描述】:

我有一个文本框,其中包含一些在进行 ajax 调用后得到的文本。 当用户键入一些文本时,我将值发送到状态。 这会呈现当前文本区域,并且光标会移到行的前面。

如何避免重新渲染。我应该如何保持状态。

class Design extends React.Component{

constructor(){
    super();
}


handleMessageChange(e){
    let msg = e.target.innerText;
    this.props.dispatch({type:'design_changed',designObj:{property:'message',value:msg}})
}
 render(){
    return  (

      <React.Fragment>

          <Panel header="Message" key="2">
            <div>
              <div className="userscoop-content-editable-cls" contentEditable="true" onKeyUp={this.handleMessageChange.bind(this)}>{this.props.message}</div>
            </div>
          </Panel>

      </React.Fragment>
 }

function mapStateToProps(state){
   let settings = state.HelloBar.template.settings;
   return {
      background_color: settings.background_color,
      action_color:settings.action_color,
      message:settings.message,
      button_color:settings.button_color,
      input_placeholder:settings.input_placeholder,
      goal:state.HelloBar.goal
    } 
}

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    如果你使用shouldComponentUpdate生命周期方法并比较新旧状态可以取消渲染。

    您也可以先尝试 PureComponent 看看是否可行。

    如果您仍然有问题,可以考虑考虑保存光标状态。 [from here]

    【讨论】:

    • 嗨!像这样 return nextProps['message'] != this.state['message'] 。我使用 this.setState({message:msg}) 设置状态,然后将值发送到 store 。触发两次通话可以吗?
    【解决方案2】:

    您可以使用组件的shouldComponentUpdate() 方法来定义它是否应该在某些道具更改时重新渲染。您可以写信忽略此更改。

    【讨论】:

    • 嗨!像这样 return nextProps['message'] != this.state['message'] 。我使用 this.setState({message:msg}) 设置状态,然后将值发送到 store 。触发两次通话可以吗?
    【解决方案3】:

    如果您正在处理需要对字段进行连续操作的组件,请尝试使用 Redux-Form。 或者在通过 keyUp 或 keyDown 触发的每个操作中使用 document.addEventListener

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2020-07-08
      • 1970-01-01
      相关资源
      最近更新 更多