React中的条件

时间:2017-01-31 22:21:54

标签: reactjs react-jsx

我已经完成了反应文档,并试图实现所有条件示例,但它似乎并没有在我的代码上工作。这是我的代码:

class Main extends React.Component {
 constructor(props) {
   super(props);
   this.onChange = this.onChange.bind(this);
   this.handleSubmit = this.handleSubmit.bind(this);
   this.state = {items: [],text: ''};
}
onChange(e) {
   this.setState({text: e.target.value});
}
handleSubmit(e) {
   e.preventDefault();
   let newItem = this.state.items;
   let text = this.state.text;
   newItem.push(text);
   let newText = '';
   this.setState({items: newItem, text: newText});
}
 render() {
  return (
    <div className="container">
     <div className="inside-box">
      <h4>Javascript Library</h4>
     </div>
     <form onSubmit={this.handleSubmit}>
       <input
         type="text"
         onChange={this.onChange}
         value={this.state.text}
         placeholder="Add your item..." />
      </form>
      {/* this will compare the input that I submitted and compare with the library. It will show result if the is a library or else it will show an error */}
      {library === this.state.items && <Result /> }
     </div>
   )
  }
}


const Result = ()  => {
    return <h1>There is a library</h1>; 
}

const Error = ()  => {
    return <h1>There is no such library</h1>; 
}


var library = ['react', 'angular', 'vue'];

ReactDOM.render(<Main />, document.getElementById('app'));

我现在有点卡住了。我尝试使用if else和三元运算符,但仍然无法正常工作。我想解析库数据的输入。这是codepen。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

这里的问题是你试图使用equals运算符比较两个数组,它总是为false。数组比较基于引用而不是值,因为这两个数组不在内存中共享相同的引用,它们不相等。

诸如Lodash之类的库提供了_.isEqual,它允许您将两个数组进行比较,否则您需要查看允许您比较两个数组的函数。

在控制台中,如果你[] === [],它将返回false作为示例。

另见How to compare arrays in JavaScript?

要解决的辅助方法是:

function arrayComparator(arr1, arr2) {
  arr1 = arr1.sort();
  arr2 = arr2.sort();
  return arr1.length === arr2.length && arr1.every(function(item, index) {
    return item === arr2[index];
  })
}

然后可以{arrayComparator(library, this.state.items) && <Result />}

一旦你有了一个对象数组,这个辅助方法就会停止工作,你也必须对它进行编程,但如果它只是将两个数组与字符串和数字进行比较,那么它将正常工作。

这是一支工作笔http://codepen.io/finalfreq/pen/GrQdEK?editors=1010

答案 1 :(得分:1)

我不清楚你在代码中想要做什么,但如果你想检查你在输入中写的是否是库,你可能需要这样的东西:{library.indexOf(this.state.text)!=-1?<Result /> :<Error/>}

编辑:

我认为你想要的是如果有一个图书馆,则分别检查州内的每个项目。因此我建议你这样:

{this.state.items.map((item)=><div>{item} {library.indexOf(item)!=-1?<Result /> :<Error/>}</div>)}

codepen