在函数内部的另一个 if 条件中读取变量的值

Reading the value of variable in another if condition inside function

我定义了从 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() {
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>
        );
}

在你的例子中

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

code inside if 语句创建一个单独的作用域,这意味着在其内部定义的任何变量都无法在外部作用域中访问。

你可以做的是将 value 变量定义移动到外部范围

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

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

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;
}

您可以简单地将可描述的附加数据添加到您的函数中 return 有效载荷

JSON数据函数:

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

渲染函数:

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