【问题标题】:Redux-form: Can't use ternary operator because object is undefined when renderingRedux-form:不能使用三元运算符,因为渲染时对象未定义
【发布时间】:2017-04-25 11:58:38
【问题描述】:

我正在使用 redux-form 让用户点击图片(激活隐藏的复选框)。一切正常,除了我想在点击图片时更改 CSS。我为此使用了三元运算符,它应该听复选框的值。我遇到的问题是,当组件最初呈现时,productValues.apps[product.name] 返回未定义。我尝试将 initialValue 设置为 false,但这也不起作用。我真的不知道如何解决这个问题。以下是复选框:

   {
      products.products.map(product => {
        return(
          <div className={ `col-xs-2 ${productValues.apps[product.name] ? "app-checked" : "app-container"}` }
               key={ product.id }>
            <label htmlFor={ product.name }>
              <img className="app-circle"
                   src={ product.image } alt={ product.title }
                   data-toggle="tooltip" data-placement="top" title={ product.title }/>

              <Field name={ `apps[${product.name}]` } className="hidden"
                    component="input" type="checkbox" id={ product.name }/>
            </label>
          </div>
        );
      })
    }

这里是我用来获取复选框数据的选择器: const 选择器 = formValueSelector('UserCreationForm');

UserCreationPageThree = connect(
  state => {
    const productValues = selector(state, ...state.products.products.map(product => `apps[${product.name}]`));

    return { productValues }
  }
)(UserCreationPageThree)

【问题讨论】:

    标签: redux react-redux redux-form


    【解决方案1】:

    添加条件,例如 -

    {(productValues && productValues.apps && productValues.apps[product.name]) ? "app-checked" : "app-container"}

    根据要求更新 Javascript World 上的 not existsundefined 之间存在差异。 undefined 表示已定义但未定义值。

    即 如果我将变量定义为-

    file_1.js

    var x;
    console.log(x); // its will display undefined on console.
    

    现在-

    file_2.js

    console.log(x); // it will throw error on 'strict mode' but on non `strict mode` javascript engine will first define `x` for you then console.log undefined.
    

    你的情况-

    productValues.apps[product.name] does not exists;
    

    【讨论】:

    • 这完全有效。谢谢。但我真的不明白为什么它不会在这里放弃同样的错误。我的意思是,productValues.apps[product.name] 在渲染时应该仍然是未定义的。在这种综合条件下,他为什么不打扰?你能解释一下吗?
    • 我编辑了我的答案。希望你能理解。
    • 感谢您的解释。非常感谢您的努力。
    猜你喜欢
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多