简体   繁体   English

如何在反应中有条件地渲染元素

[英]How to render element conditionally in react

I am using mobx + react setup for this subpage to make a searchable list of users.我正在为此子页面使用 mobx + react 设置来制作可搜索的用户列表。 My list of items is not rendering with if statement.我的项目列表未使用 if 语句呈现。 In the solution I am trying to render one of two lists in my subpage.在解决方案中,我试图在我的子页面中呈现两个列表之一。 Depending on boolean 'isSearching'.取决于布尔值“isSearching”。 First element should be shown when input field is empty, and second one is when input field has value written.当输入字段为空时应显示第一个元素,当输入字段写入值时应显示第二个元素。 They are same arrays, Only difference between lists arrays are that one of them is filtered.它们是相同的数组,列表数组之间的唯一区别是其中一个被过滤了。

Code:代码:

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

Althought if I remove condition, it works separated:虽然如果我删除条件,它会分开工作:

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


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

Store file:存储文件:

 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();

Component file:组件文件:

 @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>

Why is it not working?为什么它不起作用? On page render isSearching prop is set to false and that should effect the if statement as it is.在页面上渲染isSearching 属性设置为false ,这应该会影响 if 语句。

Issue is here, you are not checking the condition properly:问题在这里,您没有正确检查条件:

this.props.PeopleStore.people.isSearching = false

It should be:它应该是:

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

See what will happen with = , it will assign the value returned by ternary operator expression to isSearching variable.看看=会发生什么,它将三元运算符表达式返回的值分配给isSearching变量。 It will be treated like this:它将被这样处理:

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

Check this snippet:检查这个片段:

 let b = false; b = false? 1: 2; //b will become 2 console.log('b = ', b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM