[英]Why my data file cannot change when I click on the button?
I have a app that read all information from my data.json file. 我有一个应用程序,可从data.json文件中读取所有信息。 I import the file and pass by props to the components.
我导入文件并通过prop传递给组件。
I'm trying to change the language, changing my data.json import path. 我正在尝试更改语言,更改data.json导入路径。
Now I have a import data from './data/data.json'
, but I want to have two language. 现在,我
import data from './data/data.json'
,但是我想使用两种语言。 Then, I translated the data.json and create another two data files ./data/data-en.json
and ./data/data-pt.json
. 然后,我翻译了data.json并创建了另外两个数据文件
./data/data-en.json
和./data/data-pt.json
。
And made a button to change between pt
and en
. 并做了一个按钮,可以在
pt
和en
之间切换。
When I click on the button, nothing works. 当我单击按钮时,没有任何效果。
import React, { Component } from 'react';
import MyComponent from './MyComponent';
import AnotherComponent from './AnotherComponent';
import data from './data/data.json';
import english from './data/data-en.json';
import portuguese from './data/data-pt.json';
class MyApp extends Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
this.state = { data: english };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
if (this.state.isToggleOn) {
this.setState(state => ({
data: english
}))
} else {
this.setState(state => ({
data: portuguese
}))
}
console.log(data)
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'en' : 'pt'}
</button>
<MyComponent data={data.mycomponent} />
<AnotherComponent data={data.anothercomponent} />
</div>
);
}
}
export default MyApp;
How can I change my data? 如何更改我的数据?
Thanks 谢谢
The setState
is not synchronous, so in your handleClick
you should use a callback to have the new state and do your things: setState
不是同步的,因此在您的handleClick
,应使用回调函数来获取新状态并执行以下操作:
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn,
data: state.isToggleOn ? portuguese : english,
}));
console.log(data);
}
Also no need to initialize state twice in constructor so 也不需要在构造函数中初始化状态两次
Change 更改
this.state = { isToggleOn: true };
this.state = { data: english };
To 至
this.state = {
isToggleOn: true,
data: english
}
Here more information about setState
: https://reactjs.org/docs/state-and-lifecycle.html 这里有关
setState
更多信息: https : //reactjs.org/docs/state-and-lifecycle.html
I fixed my problem just puting this.state.
我解决了我的问题,只是把
this.state.
in my components: 在我的组件中:
<MyComponent data={this.state.data.mycomponent} />
<AnotherComponent data={this.state.data.anothercomponent} />
Anyway, thanks very much. 无论如何,非常感谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.