正在更新不工作的组件ReactJs

Updating component not working ReactJs

本文关键字:组件 ReactJs 工作 更新      更新时间:2023-09-26

请帮我一下,因为我被卡住了。我是新手,我正在创建一个组件,该组件从后端获取可用语言的列表并将其显示在下拉列表中,然后,一旦用户选择了一种语言,该组件就应该更新以显示所选的语言。

我面临的问题是,我不知道为什么,但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>);
}
};

问题是您实际上是在调用handleClick方法,而不是将函数作为回调分配给onClick属性。您应该从方法中删除这些括号,而是将文本作为参数传递。

onClick={component.handleClick.bind(null, result.text)}

在您的情况下,handleClick方法被调用,而不是用作回调。