1
請在這裏我需要一點幫助,因爲我卡住了。 我是新來做出反應的,我正在創建一個組件,它從後端獲取可用語言的列表,並將它們顯示到下拉列表中,然後,一旦用戶選擇了一種語言,應該更新組件以顯示所選內容一。更新組件無法正常工作ReactJs
我面對的問題是,我不知道爲什麼,但handleClick方法正在執行三次(我有三種可用的語言),無論是當頁面加載,或者當我選擇一種新的語言。因此,無論選擇什麼語言,列表中的最後一種語言都會顯示爲選中狀態。
如果你能快速瀏覽並告訴我,如果你看到可能導致這種奇怪行爲的東西,我會非常感激,因爲這件事令我瘋狂。
代碼如下:
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>);
}
};
哇,我現在明白了,現在就像一個魅力!非常感謝你的時間和幫助:) – fgonzalez
很高興它工作@fgonzalez!我之前遇到過同樣的事情,所以它在我心中是新鮮的。 –