[英]Updating component not working ReactJs
Please I would need a little bit of help here as I'm stuck. 麻烦您,在这里我需要一点帮助。 I'm new to react, and I'm creating a component that gets a list of available languages from the backend and display them into a dropdown, then, once the user selects a language, the component should be updated to display the selected one. 我是新来的人,我正在创建一个组件,该组件从后端获取可用语言的列表并将其显示在下拉菜单中,然后,一旦用户选择了一种语言,就应该更新该组件以显示所选的语言。
The problem I'm facing is that I don't know why, but the handleClick method is being executed three times(I have three available languages), either when the page is loaded, or when I select a new language. 我面临的问题是我不知道为什么,但是在页面加载或选择新语言时,handleClick方法被执行了三次(我有三种可用的语言)。 As a result, no matter what language I select, the last language in the list is always displayed as selected. 结果,无论我选择哪种语言,列表中的最后一种语言始终显示为选中状态。
Please if you can have a quick look and tell me if you see something that can lead to this strange behaviour I would appreciate very much as this thing is driving me crazy. 如果您能快速浏览一下,请告诉我是否看到导致这种奇怪行为的东西,我非常感谢,因为这件事使我发疯。
Below the code: 代码下方:
import React from 'react';
class LocaleSwitcher extends React.Component {
constructor() {
super();
this.render = this.render.bind(this);
this.handleClick = this.handleClick.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
this.state = {languages: [],selectedLocale:'En'};
//This is only printed once
console.log('constructor called');
}
handleClick(locale) {
this.state.selectedLocale=locale;
// This is printed three times,
// whenever I select a locale or when the page is loaded,why?????
console.log('Selected Locale:' + locale);
}
render() {
var component = this;
component.selectedLanguage = this.props.defaultLanguage;
return (<li>{this.state.selectedLocale}
<ul className="dropdown">
{
this.state.languages.map(function (result, i) {
var url = "data/translations?locale=" + result.text;
return (<li key={i}><a onClick={component.handleClick(result.text)} href="#">{result.text}</a>
</li>);
})
}
</ul>
</li>);
}
componentDidMount() {
var component = this;
$.get('data/languages', function (result) {
component.setState({languages: result});
});
}
};
export class LocaleCurrencySwitcher extends React.Component {
render() {
return (<ul className="switchers">
<LocaleSwitcher defaultLanguage="En"/>
</ul>);
}
};
The problem is you are actually calling the handleClick
method instead of assigning the function as a callback to the onClick
attribute. 问题是您实际上是在调用handleClick
方法,而不是将函数作为回调分配给onClick
属性。 You should remove the paratheses from the method and instead pass the text as a param. 您应该从方法中删除这些参数,而是将文本作为参数传递。
onClick={component.handleClick.bind(null, result.text)}
In your case the handleClick
method is being called instead of being used as a callback. 在您的情况下,将调用handleClick
方法,而不是将其用作回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.