【问题标题】:React Redux - element not rendering on page but React not throwing errorReact Redux - 元素未在页面上呈现但 React 未引发错误
【发布时间】:2018-01-24 00:03:17
【问题描述】:

我的 react-redux 应用似乎有问题。我目前正在使用 next.js,它在使用 redux 时往往会表现得有些奇怪,所以我不确定这是否是问题所在。也就是说,我正在尝试渲染一个循环遍历对象数组的组件。很简单。我的 mapState 函数正在工作,当我将 info 设置为 state.aboutMe[0] 时,我收到了第一个值。一旦我删除它并尝试遍历数组,最初,我收到一个错误,提示“必须返回有效的 React 元素(或 null)。您可能返回了未定义的数组或其他一些无效对象。”但我可以通过将我的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);

【问题讨论】:

  • 您的匿名箭头函数不返回任何内容。一旦你使用花括号,你就会失去隐含的回报。它不会抛出错误,因为没有错误。不相关,但我会为标题制作一个小组件,所以你最终会得到这个:gist.github.com/davelnewton/1214c9bb3f7103ff3d0264a95892c999

标签: reactjs redux react-redux


【解决方案1】:

尝试在 map 内显式使用 return。

【讨论】:

    【解决方案2】:

    应该是

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

    因为地图内的 div 并没有真正返回

    【讨论】:

    • 这会引发错误SyntaxError: Unexpected token。我相信这是因为 JSX 有一个父元素。
    • @ThomasGreco 我已经更新了代码。地图函数内不应有 {}
    • 哇!太棒了,这工作。我明白你在说什么,但我将用括号更新示例,不让人们看到。
    • 我在哪里做呢?
    • 这里。您应该会在答案的左侧看到一个复选标记。
    猜你喜欢
    • 2019-04-20
    • 2020-10-13
    • 2021-05-02
    • 2021-08-16
    • 2020-01-26
    • 1970-01-01
    • 2018-12-28
    • 2014-04-18
    • 1970-01-01
    相关资源
    最近更新 更多