如果满足条件则映射到下拉列表reactjs

时间:2020-09-24 08:47:52

标签: reactjs axios

仅在满足特定条件时,我才想填充下拉列表。 我正在使用 axios get方法来获取数据。

代码如下-

  componentDidMount = e => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then(function (res) {
        let FullData = res.data;
      });
  };

我的表格如下-

   <form>
    <select>address</select>
    <option id={FullData.zipcode}>{FullData.street}</option>
  </form>

仅当{ FullData.city }为“ Gwenborough”时,我才需要使用此功能。 请参阅here以获取JSON。

2 个答案:

答案 0 :(得分:0)

类似的事情可以帮上忙。请注意,您的问题尚不清楚,无法提供有效的示例来帮助我理解您所讨论的内容的全部范围,因此,这是我对问题解决方案的最佳猜测。

constructor(){
          this.selection=null;
          this.doSomeTesting=this.doSomeTesting.bind(this);
        }
        doSomeTesting(FullData){
           if(FullData.city ===  "Gwenborough"){   
              return (<option id={FullData.zipcode}>{FullData.street}</option>);
           }
           return ""; //return nothing useful if not what you're looking for
        }
         componentDidMount=(e)=>{
            axios.get('https://jsonplaceholder.typicode.com/users')
                .then(function(res){
                    let FullData=res.data
                    this.selection = this.doSomeTesting(FullData);
                })
          }
    
        render(){
            <form>
            <select>address</select>
              {this.selection}
             </form>
         }

答案 1 :(得分:0)

这是一种方法。通常,您需要将值置于状态,以便每当以异步方式接收它们时,组件都会被更新。

这里是Demo sandbox

class DropDown extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      FullData: [],
    }
  }
  componentDidMount=(e)=>{
    fetch('https://jsonplaceholder.typicode.com/users')
        .then(res => res.json())
        .then(res => {
            this.setState({
              FullData: res
            }) 
        })
  }

  render() {
    let { FullData } = this.state;
    return (
      <form>
          <label>Address </label>
          <select>
            {FullData
              .filter(user => user.address.city === "Gwenborough")
              .map(user => {
              return <option key={user.id} id={user.zipcode}>{user.address.street}</option>
            })}

          </select>
       
      </form>
    );
  }
}
 

请注意,我使用的是fetch而不是axios。 另一个注意事项-我真的很喜欢Dexter的回答以及将动作放入单独功能的方式。通常,这似乎是一种更好的结构化代码的方法。它可能行不通,因为仅是因为您的数据结构如何:您获得并排列了用户,并且在city键中只有streetaddress。干杯!

相关问题