我想遍历数组并动态输出结果。如果没有匹配项,我想输出另一个结果

时间:2019-07-10 16:47:23

标签: javascript arrays reactjs

我有一个对象数组,当用户输入一个邮政编码并单击“我要遍历该数组”时,如果用户邮政编码与数组输出结果中的邮政编码匹配,如果该邮政编码与输出结果不匹配,则返回另一个结果

我试图在数组上使用map和forEach,每一个都允许我找到邮政编码,并在邮政编码不匹配时给我带来麻烦

class PricingTool extends Component {
  state = {
    zipCode: "",
    finalZip: "",
    routine: "",
    rush: "",
    sameDay: "",
    city: "",
    match: false
  };

  handleKeypress = e => {
    const { zipCode } = this.state;
    if (e.which === 13 && zipCode.length === 5) {
      console.log("enterrerre");
      this.zipcodeHandler();
    }
  };

  zipcodeHandler = () => {
    const { zipCode } = this.state;
    this.setState({
      finalZip: zipCode,

    });
  };

  changeHandler = e => {
    e.preventDefault();

    if (e.target.value.length <= 5 && !isNaN(e.target.value)) {
      this.setState({
        [e.target.name]: e.target.value
      });
    }
  };

  render() {
    const { finalZip, zipCode, match } = this.state;
    let searchResult;

    if(finalZip){
      searchResult = zipCodes.map(cur => {
      if (finalZip && finalZip == cur.zip) {        
        return (
          <div className="pricing__searchResult">
            <h1 className="pricing__searchResult-1">
              We do serve in {cur.city}, Indiana
            </h1>
            <div className="pricing__searchResult-2">Same-Day</div>
            <div className="pricing__searchResult-3">{cur.fees.sameDay}</div>
            <div className="pricing__searchResult-4">Rush</div>
            <div className="pricing__searchResult-5">{cur.fees.rush}</div>
            <div className="pricing__searchResult-6">Routine</div>
            <div className="pricing__searchResult-7">{cur.fees.routine}</div>
            <div className="pricing__searchResult-8">
              Please call us or email info@ccprocess.com to order
            </div>
          </div>
        );
      }
    });
    }

我希望它找到用户输入的邮政编码,如果它在数据数组中,如果没有,则呈现另一条消息

2 个答案:

答案 0 :(得分:1)

与其使用Array map方法(该方法会将数组的每个值映射到其他值)(在您的情况下,它只会映射找到的邮政编码),您可以(并且应该)使用更好的方法为了工作。 find方法将找到符合条件的第一个项目并将其返回,在您的情况下,它可能是finalZip && (finalZip == cur.zip)。如果找不到给定表达式的项,则返回undefined

render() {
    const { finalZip, zipCode, match } = this.state;
    let searchResult;

    if(finalZip){
      searchResult = zipCodes.find(cur => finalZip && (finalZip == cur.zip));
      if(searchResult) {
          // do something for when the zip code is found
      }
      else {
          // do something when no zip code is found
      }
    }
}

数组find方法文档:MDN

答案 1 :(得分:0)

不确定所使用的组件或当前应用程序中的所有组件,我创建了一个示例应用程序,可以模拟您的需求并可能提供正确的输出。

因此,在这里,我不知道将在哪里从用户那里获取输入以及您的onKeyPress侦听器将如何工作,因此我创建了另一个组件,该组件根据输入呈现您的数据,并检查邮政编码是否存在。

就像下面所示,与ZipCode相关的信息将由另一个组件ZipTool呈现,而您的输入框由PricingTool处理

此外,如果您想使用以下代码-https://jsfiddle.net/hf9Ly6o7/3/

,这里是jsfiddle

我希望您觉得这有用。

class ZipTool extends React.Component {
	constructor(props) {
  	super(props);
  }
	render() {
  	let { data } = this.props;
  	return (
    	<div>
        <h1 className="pricing__searchResult-1">We do serve in { data.city }, Indiana</h1>
        <div className="pricing__searchResult-2">Same-Day</div>
        <div className="pricing__searchResult-3">{ data.fees.sameDay }</div>
        <div className="pricing__searchResult-4">Rush</div>
        <div className="pricing__searchResult-5">{ data.fees.rush }</div>
        <div className="pricing__searchResult-6">Routine</div>
        <div className="pricing__searchResult-7">{ data.fees.routine }</div>
      </div>
    );
  }
}

class PricingTool  extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    	zipCodes: [
      						{
                  	'zipcode': '12345', 
                    'city': 'abc', 
                    'fees': {
                    	'sameDay': '43', 
                      'rush': '90', 
                      'routine': '20'
                    }
                  },
                  {
                  	'zipcode': '54321', 
                    'city': 'xyz', 
                    'fees': {
                    	'sameDay': '25', 
                      'rush': '35', 
                      'routine': '10'
                    }
                  }
      					],
    	zipCode: "",
      finalZip: "",
      routine: "",
      rush: "",
      sameDay: "",
      city: "",
      match: false
    }
    
  }
 
  
  changeHandler(e) {

     this.setState({
        zipCode: e.target.value,
      });
      
      for (let code of this.state.zipCodes) {
        if( code.zipcode === e.target.value ){
          this.setState({match: true, finalZip: code})
          break;
        }
        else {
          this.setState({match: false, finalZip: null})
        }
      }
    
  };
  
  render() {
    return (
    	<div>
        <input type="text" onChange={this.changeHandler.bind(this)} onKeyPress={this.handleKeyPress} name={this.state.zipCode}></input>
        <div className="pricing__searchResult">
          { this.state.finalZip ? <ZipTool data={this.state.finalZip} /> : <div>Not Found</div> }
          <div className="pricing__searchResult-8">
            Please call us or email info@ccprocess.com to order
          </div>
        </div>
      </div>
    )
  }
}

ReactDOM.render(<PricingTool  />, document.querySelector("#app"))
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.done {
  color: rgba(0, 0, 0, 0.3);
  text-decoration: line-through;
}

input {
  margin-right: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>