【发布时间】: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