简体   繁体   English

为什么单击按钮后 forceUpdate 不起作用?

[英]Why forceUpdate doesn't work after click button?

I'm doing a little project using ag-agrid and I'm trying to translate it.我正在使用 ag-agrid 做一个小项目,我正在尝试翻译它。

My objetive is when user click in a button it change the language and to change the language the page must be refreshed我的目标是当用户单击按钮时,它会更改语言并更改页面必须刷新的语言

when click on button:点击按钮时:

changeLanguage(lang) {
    this.setState({language: lang},
    this.forceUpdate());
  }

the problem is:问题是:

forceUpdate() is not working forceUpdate() 不起作用

render and construtor:渲染和构造器:

constructor(props) {
    super(props);

    this.state ={
       language: 'pt'
    }

    this.changeLanguage = this.changeLanguage.bind(this);
}


render() {
  return (
<div className="ag-theme-balham" style={{ height: '700px', width: '95%' }}>

  <Row>
    <Button onClick={() => this.changeLanguage('pt')}> PT </Button>
    <Button onClick={() => this.changeLanguage('en')}> EN </Button>                
  </Row>

  <br/>

  <AgGridReact
     //props of grid
     localeText={this.state.language === 'pt' ? pt : en}

  />
</div>
);
}

I'm doing something wrong when I'm using forceUpdate?我在使用 forceUpdate 时做错了什么?

codeSandBox代码沙盒

Note: pt and en are data from a json file注意:pt 和 en 是来自 json 文件的数据

You can trigger a re-render by adding a key property in combination with this.state.language to the AgGridReact component instead of using this.forceUpdate() .您可以通过将key属性与this.state.languageAgGridReact组件而不是使用this.forceUpdate()来触发重新渲染。 This should cause a re-render when you change the language via the button clicks:当您通过单击按钮更改语言时,这应该会导致重新渲染:

<AgGridReact
  key={this.state.language}
  ... other props
/>

Here is an example in action.这是一个实际的例子

I don't see any issues with your code, this seems like more of an issue with the grid component failing to update.我没有看到您的代码有任何问题,这似乎更像是网格组件无法更新的问题。 You are updating state correctly.您正在正确更新 state。

Hopefully that helps!希望这会有所帮助!

according to Reactjs documentation, re-rendering happens automatically, every time the state gets updated and you don't need to do it manually: https://reactjs.org/docs/react-component.html#forceupdate根据 Reactjs 文档,重新渲染会自动发生,每次 state 得到更新并且您不需要手动进行: https.htmlupdate/docs

however, if you want to add a callback to a state updater, you should use this syntax:但是,如果您想向 state 更新程序添加回调,您应该使用以下语法:

changeLanguage(lang) {
    this.setState({language: lang}, () => {
        this.forceUpdate()
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM