【问题标题】:Calling a method from Array.map React从 Array.map React 调用方法
【发布时间】:2018-09-17 20:00:52
【问题描述】:

我想创建一个简单的函数,将数组对象的索引转换为字母并在我的反应组件中呈现它。但是我遇到了一个问题。
我的代码是:

 class StringList extends Component {
  state = {
    strings: ['String1', 'String2', 'String3', 'String4', ]
  }

  numToChar =i=> {
    return (i >= 26 ? this.numToChar((i / 26 >> 0) - 1) : '') + 'abcdefghijklmnopqrstuvwxyz'[i % 26 >> 0];
  }

  render(){
    return(
      <div> 
        {this.state.strings.map((string, index) => (
            <p>
            {index}, 
            {this.numToChar({index})},
            {this.numToChar(5)}
            //Do other Stuff
          </p>
        ))}
      </div>
    )
  }
}

我希望结果是:
0, a, f
1、b、f
2、c、f
3、d、f
...
但这实际上会返回:
0, a, f
1、a、f
2、a、f
3、a、f
...
它正确地增加了索引,但当我使用它来调用我的方法时却没有。这是因为进程是异步的吗?如果是这样,我如何在反应渲染组件方法中使用等待或承诺?还是有另一种方法我应该这样做?我还很陌生,所以任何其他信息都会有所帮助。

【问题讨论】:

  • 您将一个对象 ({index}) 传递给您的函数,而不是 index
  • 好吧,我是个白痴。 Ty 有帮助。@Shobhit Chittora

标签: arrays node.js reactjs asynchronous


【解决方案1】:

React 中的 Render 方法应该是纯的,你应该在它之外做异步工作。无论如何,这不是您的问题所必需的。

这里是解决方案的链接。 https://codesandbox.io/s/jv4w87z7vv

与其编写将整数映射到字符的复杂方法, 你可以简单地使用String.fromCharCode(97 + n)

你也将索引作为对象传递this.numToChar({index}) 而它只是一个变量this.numToChar(index)

【讨论】:

  • Ty,是的,问题是我使用索引作为对象,而不是作为变量。 97+n 方法很棒,但我可能有超过 26 个元素,其中 aa、ab、ac... 比继续使用其他 ASCII 字符更可取
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 2022-07-26
  • 2018-07-20
相关资源
最近更新 更多