javascript - 如何在 react 中有条件地渲染元素

标签 javascript reactjs if-statement mobx mobx-react

我正在为此子页面使用 mobx + react 设置来制作可搜索的用户列表。我的项目列表未使用 if 语句呈现。在解决方案中,我试图在我的子页面中呈现两个列表之一。取决于 bool 值“isSearching”。当输入字段为空时应显示第一个元素,当输入字段写入值时应显示第二个元素。它们是相同的数组,列表数组之间的唯一区别是其中一个被过滤。

代码:

 <ul className='items__block'>
    {
        this.props.PeopleStore.people.isSearching = false ?
            (this.props.PeopleStore.people.map(this.person))
        : 
            (this.props.PeopleStore.searchingList.map(this.person))
    }
</ul>

尽管我删除了条件,但它分开工作:

<ul className='items__block'>
    {
       this.props.PeopleStore.people.map(this.person)
    }
</ul>


<ul className='items__block'>
    {
       this.props.PeopleStore.people.map(this.person)
    }
</ul>

存储文件:

 import { runInAction, observable, action, toJS } from 'mobx';
    // ES7 compiler
    import regeneratorRuntime from 'regenerator-runtime';

    class PeopleStore {
        @observable people = [];
        @observable loading = false;
        @observable isSearching = false;
        @observable searchingList = [];

    // API call
    loadPeople = async() => {
        this.loading = true;
        const response = await fetch('https://randomuser.me/api/?results=71');
        const json = await response.json();
        runInAction(() => {
            this.people = json.results;
        });
        this.loading = false;
        console.log(toJS(this.people));
    }

    // this function is called by onChange event
    @action.bound filterList = textTyped => {
       // changing boolean to identify if input is empty or not
        if (textTyped.target.value.length < 1) {
            this.isSearching = false;
        } else {
            this.isSearching = true;
        }
        
        console.log(this.isSearching);
        
        let peoplesNames = [];
        for (let i = 0; i < this.people.length; i++) {
            peoplesNames.push(toJS(this.people[i]));
        }
        peoplesNames = peoplesNames.filter(function(item) {
            return item.name.first.toLowerCase().search(textTyped.target.value.toLowerCase()) !== -1
        });
        
        this.searchingList = peoplesNames;
    // tracking both arrays, they both work
        console.log(toJS(this.searchingList));
        console.log(toJS(this.people));
        }
    }

    export default new PeopleStore();

组件文件:

@inject('showHandler', 'PeopleStore') @observer
    class PickList extends React.Component {
    
    componentWillMount() {
        this.props.PeopleStore.loadPeople();
    }
    
    
    person = ({name, picture}, index) =>
        <li className="items__block--user" key={index} onClick={this.props.PeopleStore.selectPerson}>
            <img className="user--image" src={picture.medium} alt="face" />
            <span className="user--name">{`${name.first} ${name.last}`}</span>
        </li>;

    render() {
        if (this.props.PeopleStore.loading) {
            return (
                <div className="loader"></div>
            );
        }

        return (
            <React.Fragment>
                <input className="users__block--input" onChange={this.props.PeopleStore.filterList}></input>
                <ul className='items__block'>
                    {
                    this.props.PeopleStore.people.isSearching = false //checks mobx prop
                    ?
                    (this.props.PeopleStore.people.map(this.person))
                    : 
                    (this.props.PeopleStore.searchingList.map(this.person))
                    }
                </ul>

为什么它不起作用?在页面渲染中,isSearching 属性设置为 false,这应该会影响 if 语句。

最佳答案

问题在这里,您没有正确检查条件:

this.props.PeopleStore.people.isSearching = false

应该是:

this.props.PeopleStore.people.isSearching == false      // notice "=="

看看 = 会发生什么,它会将三元运算符表达式返回的值分配给 isSearching 变量。它将被这样处理:

isSearching = (false? 1: 2);   // isSearching will get a new value, and second expression will get executed always

检查这个片段:

let b = false;
b = false? 1: 2;   //b will become 2

console.log('b = ', b);

关于javascript - 如何在 react 中有条件地渲染元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48975515/

相关文章:

javascript - 从 AngularJS 服务传递数据

javascript - 在 Node.js 中,setTimeout() 是否会阻塞事件循环?

javascript - Polymer 中是否支持带有破折号的属性和属性?

reactjs - 如何获得 react 代码的完整测试覆盖率

javascript - 将表示任意基数的字符串转换为数字

javascript - React - 关于日期格式的控制台错误 - "Objects are not valid as a React child"

javascript - 单击图标时如何在用户对象内设置 userId

java - 为什么一旦 run() 方法中的 if 语句为 true,我就不能再使用 keyPressed 了?

python - 尽管满足条件,但字符串上的 for 循环的 if 语句仍不起作用

c - 在 C 语言中 if(x) 到底解析成什么?