Redux 形式:不能使用三元运算符,因为渲染时对象未定义

Redux-form: Can't use ternary operator because object is undefined when rendering

我正在使用 redux-form 让用户点击图片(以激活隐藏的复选框)。一切正常,除了我想在单击图片时更改 css。我为此使用了一个三元运算符,它应该监听复选框的值。我遇到的问题是,当组件最初呈现时,productValues.apps[product.name] returns 未定义。我尝试将 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>
        );
      })
    }

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

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

    return { productValues }
  }
)(UserCreationPageThree)

添加条件如 -

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

根据要求更新 not existsundefinedJavascript World 上有区别。 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;