使用无状态组件进行条件渲染时出错

时间:2018-08-16 07:21:15

标签: reactjs

当我检查项目的长度,并尝试添加到模板中时,出现错误。有人可以帮助我解决此问题吗?

这是我的代码:

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 00);
c.set(Calendar.SECOND, 00);

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        //Call your method here
        //setEmail(emailContent, subject);
    }
}, c.getTime(), 86400000);

//24hrs == 86400000ms

获取错误为import React from "react"; import "./style-posts.css"; import { connect } from "react-redux"; import { setTitle, titleHandler } from "../actions/postActions"; const ShowPosts = props => { if (props.posts.length) { const postItems = props.posts.map(post => { <div key={post.id}> <h3>{post.title}</h3> <p>{post.body}</p> </div>; }); } return ( <div> {props.posts.length ? postItems : null} //postItems is not defined <button onClick={props.showPosts}>Show Posts On Click </button> </div> ); }; export default connect( setTitle, titleHandler )(ShowPosts); -我的代码有什么问题?有人知道吗?

2 个答案:

答案 0 :(得分:0)

这是因为postItems是一个常量,并且您在if块内定义了postItems变量,因此它仅在该块中可用。 (let和const具有块范围,而var具有功能级范围。)

这样写:

let postItems = null;

if (props.posts.length) {
    postItems = props.posts.map(post => (
        <div key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.body}</p>
        </div>;
    ));
}

或者使用var代替const

if (props.posts.length) {
    var postItems = props.posts.map(post => (
        <div key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.body}</p>
        </div>;
    ));
}

我建议检查此答案以了解let,var和const之间的区别:

What's the difference between using "let" and "var" to declare a variable in JavaScript?

答案 1 :(得分:0)

可以是常量

const postItems = !props.posts.length ? []
  : props.posts.map(post => (
    <div key={post.id}>
      <h3>{post.title}</h3>
      <p>{post.body}</p>
    </div>;
  ));

没有渲染数据,因为没有mapStateToProps,没有正确的mapDispatchToProps,仅仅是错误的connect使用。