How to render react components by using map and join?

后端 未结 14 2198
南旧
南旧 2020-12-07 15:30

I have one component which is going to display Array of String. The code looks like this:

React.createClass({
  render() {
     
this.props
14条回答
  •  半阙折子戏
    2020-12-07 15:57

    Am I the only who thinks there's a lot of needless spreading and nesting going on in the answers here? Points for being concise, sure, but it leaves the door open to issues of scale or React changing how they deal with nested arrays/Fragments.

    const joinJsxArray = (arr, joinWith) => {
      if (!arr || arr.length < 2) { return arr; }
    
      const out = [arr[0]];
      for (let i = 1; i < arr.length; i += 1) {
        out.push(joinWith, arr[i]);
      }
      return out;
    };
    
    // render()
    
    {joinJsxArray(this.props.data.map(t => t), ', ')}

    One array, no nesting. No sexy method chaining either, but if you find yourself doing this often you can always add it to the array prototype or wrap it in a function that takes a mapping callback as well to do it all in one go.

提交回复
热议问题