【问题标题】:Issue rendering a unsorted list in reactjs在 reactjs 中渲染未排序列表的问题
【发布时间】:2016-01-31 22:11:43
【问题描述】:

我需要一个 react js 专家来帮助我解决这个问题。

我正在学习 react js,作为第一次尝试,我想创建一个代表两个选择框的组件,一个用于不同的货币,另一个用于应用程序中允许的不同语言。

所以我创建了一个组件“ListItemWrapper”,它代表一个 li html 元素和一个代表两个选择框的“LanguageCurrencySwitcher”。

调用服务器以获取货币和语言工作正常,信息检索正确。

一旦进入客户端,我需要遍历这两个列表来创建“li”html 元素。在迭代过程中,如果我使用“console.log(result);”输出值,则值会在控制台中正确打印。 但是组件 ListItemWrapper 没有被显示,所以列表没有被填充,但是如果我尝试在循环之外显示 ListItemWrapper,“li”元素会正确显示。

我错过了什么?谁能告诉我如何解决这个问题?

代码下方:

var ListItemWrapper = React.createClass({

render: function () {
    console.log("title:" + this.props.title);
    return <li onClick={this.handleClick}><a href="#">{this.props.title}</a></li>
},

handleClick: function (event) {
    console.log(event.target);
}
});


var LanguageCurrencySwitcher = React.createClass({


getInitialState: function () {

    return {data: {currencies: [], languages: []}};

},

render: function () {
    return <ul className="switchers">
        <li>$
            <ul className="dropdown">
                {
                    this.state.data.currencies.forEach(function(result){
                        console.log(result);
                        <ListItemWrapper title={result} />
                    })
                }
            </ul>
        </li>
        <li>En
            <ul className="dropdown">
                {
                    this.state.data.languages.forEach(function(result){
                        console.log(result);
                        <ListItemWrapper  title={result} />
                    })

                }
            </ul>
        </li>
    </ul>
},


componentDidMount: function () {
    $.get('/std/rest/data/switchers', function (result) {
        console.log(result);
        if (this.isMounted()) this.setState({data: result});
    }.bind(this));
},




});


ReactDOM.render(
<LanguageCurrencySwitcher/>,
document.getElementById('language-currency-switcher')
);

【问题讨论】:

    标签: javascript jquery html reactjs


    【解决方案1】:

    当你应该使用.map()时,你正在使用.forEach()

    你应该这样做

    this.state.data.currencies.map(function(result){
      return <ListItemWrapper title={result} />;
    })
    

    Array::map

    【讨论】:

    • 哦啦啦,真的,我的错。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多