【问题标题】:Access Redux State Object Property in Function在函数中访问 Redux 状态对象属性
【发布时间】:2016-06-01 04:58:53
【问题描述】:

我的 react 组件中有一个内联函数,设置如下:

render() {
    const { post } = this.props;

    return (
        <div>
            {function(){
                if ({post}) {
                    return <h1>Post name exists {post.name}</h1>
                } else {
                    return <h1> Post name does not exist</h1>
                }
            }.call(this)}
     .....

我有这样的 redux 状态设置:

function mapStateToProps(state) {
    return { 
        post:state.post.single,
    };
}

上面的代码有效,但我真正想检查的是 post.name 是否为空,在这种情况下,我会在页面上呈现不同的内容。但是,当我这样做时,我不断收到错误:

if({post.name})

【问题讨论】:

  • @AvraamMavridis 是说“。”在 {post.name} 中是一个意外的标记。

标签: function reactjs state redux


【解决方案1】:

您正在尝试提取 if 内的对象的值,您不能这样做,例如:

function something(post){
  if({ post.name })
  {

  }

}

甚至

function something(post){
  if({ post})
  {

  }

}

不是有效的js,可以在babel repl查看

你能做的是

const { post : { name } } = this.props;

然后检查if(name)

【讨论】:

  • 谢谢,我尝试了这种方法,但出现错误:无法读取 null 的属性“名称”
  • @lost9123193 所以你的映射有问题,你没有将状态传递给组件。你在使用connect 和选择器吗?
  • 啊,明白了。我相信它已连接,因为我能够在渲染方法中执行此操作:

    {post.name}

    我将选择器用于什么?
  • 我无法从您的代码中看到post.nameCannot read property 'name' of null 如何在您执行const { post : { name } } = this.props; 时同时拥有Cannot read property 'name' of null
  • 我也不确定,但我尝试了其他方法并使其正常工作。感谢您的建议
【解决方案2】:

您好,如果您必须进行一些测试,使用 renderCheck 函数是一个不错的方法。但是你必须仔细检查 props.post 和 props.post.name :( 为了避免这种“嵌套”检查,我正在使用 ImmutableJS,然后在我的连接中我会有

name: state.getIn(['post'], ['name'])

这将返回未定义的帖子或名称未定义或为空:)

【讨论】:

  • 感谢您的建议!我会把它放在 renderCheck 函数中吗?
  • 如果您的状态是不可变友好的,您可以直接在连接中使用它,我认为是这样的:` function mapStateToProps(state) { return { postName: state.getIn(['post', 'single ', '姓名']), }; } `
【解决方案3】:

我设法通过调用函数而不是进行内联调用来使其工作:

renderCheck(){
    if(this.props.post.name){
      return (
        <div>
          ....
        </div>
      )
    }
 }

在渲染中我这样称呼它:

 {this.renderCheck()}

我仍然不确定为什么 const { post : { name } } = this.props;没有用,但我现在将使用它。

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2018-07-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多