React Redux - 元素不在页面上呈现但React没有抛出错误

时间:2017-08-16 00:45:46

标签: reactjs redux react-redux

我的react-redux应用程序似乎遇到了问题。我目前正在使用next.js,在使用redux时往往会有点奇怪,所以我不确定这是不是问题。也就是说,我正在尝试渲染一个循环遍历对象数组的组件。非常简单。我的mapState函数正常工作,当我将信息设置为state.aboutMe[0]时,我收到了第一个值。一旦我删除它并尝试迭代数组,最初,我得到一个错误,说“必须返回一个有效的React元素(或null)。你可能已经返回undefined,一个数组或一些其他无效的对象。”但我能够通过将info.map包裹在<div> el。

中来解决这个问题

我检查了其他问题并在扩展React.Component类的类中重构了我的函数,但迭代仍然没有运气。在这种情况下,它只是在屏幕上不打印任何内容。我也在底部添加了代码。如果我能搞清楚,请告诉我。提前谢谢!

// This code IS working
// Needed to wrap inner return statement in JSX
const heading = ({info}) => {
    console.log(info);
    return (
    <div>{
    info.map(x => {
    return ( 
      <div>
        <h2>{x.title}</h2>
      </div>
    )
    }) 
  }
    </div>
  )
  }

  // Same code without inner return 
  const heading = ({info}) => {
    console.log(info);
    return (
    <div>
      {
        info.map(x => (
          <div>
            <h2>{x.title}</h2>
          </div>
          )
        )
      }
    </div>
  )
}

// prints info in console
    const heading = ({info}) => {
   console.log(info);
  return (
    <div>{
    info.map(x => {
    <div>
      <h2>{x.title}</h2>
    </div>
    }) 
  }
    </div>
  )
}

const mapState = state => ({ info: state.aboutMe })
const Heading = connect(mapState)(heading);

// EXAMPLE WITH CLASS
// Prints nothing to the screen but doesnt throw error
class homePage extends React.Component {
  render() {
    const { info } = this.props;
    console.log(info);
    return (
      <div> {
      info.map(x => {
        <div>
          <h2>{x.title}</h2><p>{x.text}</p>
        </div>
      })
      }
      </div>
    )
  }
}
const mapState = state => ({ info: state.aboutMe })
const Heading = connect(mapState)(homePage);

2 个答案:

答案 0 :(得分:1)

应该是

return (
  <div>
    {info.map(x => (<div>
      <h2>{x.title}</h2><p>{x.text}</p>
    </div>)
    )}
  </div>
)

因为地图中的div实际上并没有被返回

答案 1 :(得分:0)

尝试显式使用返回内部地图。