【问题标题】:Reading the value of variable in another if condition inside function在函数内部的另一个 if 条件中读取变量的值
【发布时间】:2019-02-10 10:02:04
【问题描述】:

我定义了从 JSON 获取数据并将其传递给渲染的函数。但我不得不提出 2 个不同的条件来处理数据。

下面是函数:

filterItems = () => {
 let result = [];
 const { searchInput } = this.state;
 const filterbrandsnew = this.props.tvfilter.brand;
 if (filterbrandsnew) {
 let value = filterbrandsnew[0].options.map(({catgeory_name})=>catgeory_name);
 console.log (value);
 }
 const brand = value;
 if (searchInput) {
    result = this.elementContainsSearchString(searchInput, brand);
 } else {
    result = brand || [];
 }
 return result;
}

我想在这个 const const brand = value; 中有值

在 render 方法中访问数据如下:

render() {
const filteredList = this.filterItems();
return (
            <div className="filter-options">
                <ul className="languages">
                    {filteredList.map(lang => (
                        <li
                            className={lang === this.props.selectedLanguage ? 'selected' : ''}
                            onClick={this.props.onSelect.bind(null, lang)}
                            key={lang}
                        >
                            {lang}
                        </li>
                    ))}
                </ul>
            </div>
        );
}

【问题讨论】:

  • 你在问如何分配const brand = value

标签: javascript arrays json reactjs ecmascript-6


【解决方案1】:

在你的例子中

if (filterbrandsnew) {
 let value = filterbrandsnew[0].options.map(({catgeory_name})=>catgeory_name);
 console.log (value);
}

if 语句中的代码创建了一个单独的作用域,这意味着在它内部定义的任何变量都不能在外部作用域中访问。

您可以做的是将value 变量定义移至外部范围

let value
if (filterbrandsnew) {
 value = filterbrandsnew[0].options.map(({catgeory_name})=>catgeory_name);
 console.log (value);
}

这样value 将包含undefined(如果它从未输入过if 语句),或者如果它输入了您需要的结果。

【讨论】:

    【解决方案2】:

    您可以简单地将可描述的附加数据添加到您的函数返回负载

    JSON数据函数:

    filterItems = () => {
     ...
     return { items: result, brand: value };
    }
    

    渲染函数:

    render() {
    const filteredHandler = this.filterItems();
    const filteredList = filteredHandler.items;
    const brand = filteredHandler.brand;
    ...
    

    【讨论】:

      【解决方案3】:

      if 块之外声明value

      filterItems = () => {
       let result = [];
       const { searchInput } = this.state;
       const filterbrandsnew = this.props.tvfilter.brand;
       let value;
       if (filterbrandsnew) {
          value = filterbrandsnew[0].options.map(({catgeory_name})=>catgeory_name);
          console.log (value);
       }
       const brand = value;
       if (searchInput) {
          result = this.elementContainsSearchString(searchInput, brand);
       } else {
          result = brand || [];
       }
       return result;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-07-31
        • 2014-12-06
        • 1970-01-01
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 1970-01-01
        • 2012-04-25
        • 1970-01-01
        相关资源
        最近更新 更多