【问题标题】:Is it possible to get values for <options> from an endpoint that sends back json response using axios?是否可以从使用 axios 发回 json 响应的端点获取 <options> 的值?
【发布时间】:2018-09-19 05:30:26
【问题描述】:

所以,我有这个端点:http://127.0.0.1:8000/api/materials 这将返回这个 json 响应:

{
"data": [
    {
        "uuid": "05a36470-d0a0-11e7-91b4-ff3d7d9f961a",
        "title": "Apple",
        "viewing_time": 15,
        "description": "",
        "organization_id": null,
        "created_at": "2017-11-24 06:45:36",
        "updated_at": "2017-11-24 06:45:36",
        "deleted_at": null
    },


    {
        "uuid": "2048f730-bfa0-11e7-95fb-6dceb95ba437",
        "title": "Banana",
        "viewing_time": 15,
        "description": "It's a fruit",
        "organization_id": null,
        "created_at": "2017-11-02 15:33:31",
        "updated_at": "2017-11-02 15:33:31",
        "deleted_at": null
    },


    {
        "uuid": "3b6a1020-d0a0-11e7-b6bb-d77fc76d610b",
        "title": "Strawberry",
        "viewing_time": 15,
        "description": "",
        "organization_id": null,
        "created_at": "2017-11-24 06:47:06",
        "updated_at": "2017-11-24 06:47:06",
        "deleted_at": null,
    },

我想选择所有的标题并让它们成为选项。 这是我调用 axios 的函数:

materialList = () => {
    var token = localStorage.getItem('jwt');
    var apiBaseUrl = "http://127.0.0.1:8000/api/materials";

    var config = {
      headers: {
        'Authorization': "bearer " + token,
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      withCredentials: false
    }

    axios.get(apiBaseUrl, config)
    .then(function (response) {
      console.log(response);

  })
  .catch(function (error) {
  console.log(error);
  });
  }

这是我希望标题(Apple、Banana 和 Strawberry)出现的地方:

            <Form.Input list='material' placeholder='Material' name="material_id" id="material_id" onChange={this.onChange}/>
            <datalist id='material_id'>
                <option value=/** What do I put here **/ />

            </datalist>

我在向api提交post请求时使用了axios,但是我可以在页面加载后立即触发axios get请求,以便获得我需要的标题吗?

【问题讨论】:

    标签: javascript reactjs semantic-ui-react


    【解决方案1】:

    首先在您的组件中创建如下所示的状态变量。

    constructor(props) {
        super(props);
        this.state = {
            options: []
        }
    }
    

    现在,您可以使用 componentDidMount() 从 API 获取这些值,如下所示。

    componentDidMount() {
     const token = localStorage.getItem('jwt');
    
     const apiBaseUrl = "http://127.0.0.1:8000/api/materials";
    
     const config = {
      headers: {
        'Authorization': "bearer " + token,
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
     }
    
     axios.get(apiBaseUrl, config)
      .then((response) => {
        this.setState({
          options: response.data
        })
       })
      .catch((error) => {
        console.log(error);
       });
    }
    

    现在您可以使用该状态变量在选项中显示。

    render() {
     const { options } = this.state;
    
     return(
      <Form.Input list='material' placeholder='Material' name="material_id" id="material_id" onChange={this.onChange}>
       {options.map((item, index) => <option key={index} value={item.uuid}>{item.title}</option>)}
      </Form.Input>
     )
    }
    

    【讨论】:

    • 但现在它说,TypeError: options.map is not a function
    • 像这样使用它:{options &amp;&amp; options.map((item, index) =&gt; &lt;option key={index} value={item.uuid}&gt;{item.title}&lt;/option&gt;)}
    • 而且,您可以使用 html Select 标签而不是 Form.Input
    • 首先检查你得到什么回应?出现该错误是因为选项中没有数据,因此请检查您是否从 axios 正确获取响应
    • 我已经根据您提供的 json 响应设置了 response.data 选项。所以检查一下是否正确
    【解决方案2】:

    首先,将options 数组添加到您的状态。

    接下来,在你的 axios 函数中:

    axios.get(apiBaseUrl, config)
    .then(response => {
        this.setState({
            options: response.data.map(item => item.title),
        });
    })
    

    最后,在您的 UI 组件中(假设您已将之前的 options 作为同名变量提供):

    const optionList = options.map(option => <option value={option} />)
    
    render() {
        return (
            // Other JSX here..
            <datalist id='material_id'>
               {optionList}
            </datalist>
        )
    }
    

    【讨论】:

      【解决方案3】:

      我假设您发布的 jsx 代码是您的组件渲染函数中的内容。

      如果您需要来自外部源的数据,并且想要在组件安装时发出 http 请求以获取这些数据。您可能想要做的是获取componentDidMount 中的数据,将其保存到您的状态,然后在您的渲染函数中使用它,可以在下面找到一个示例:

      class YourComponent {
          // Use componentDidMount to get the data via axios
          componentDidMount() {
              // ... Your code to prepare the axios call
      
              /* 
               * Use arrow function to keep refer to React component `this`
               * and sae the response data to the component state
               */
              axios.get(apiBaseUrl, config)
                .then(
                   response => this.setState({options: response.data})
                )
                .catch(function (error) {
                   // handle the error here
                });
          }
      
          render() {
              // Options will have the same format as your response data
              const { options } = this.state;
      
              return (<datalist id='material_id'>
                  {options.map(option =>  
                     <option value={/* can be any attribute you want from the result object, like id, title, ..etc*/}>
                       {option.title}
                     </option>)}
              </datalist>);
          }
      }
      

      【讨论】:

      • 但现在它说 TypeError: options.map is not a function
      【解决方案4】:

      关于页面加载时API请求的触发: 让自己熟悉 React 生命周期方法。 https://reactjs.org/docs/react-component.html

      在这种情况下,我会选择 componentDidMount() 方法:

      componentDidMount() {
        this.materialList();
      }
      

      如果您不打算使用 redux 来保存状态,您可能需要在此处调用 setState() 以便将请求的结果保存在组件的状态中(如 Nico 所述)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-04
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 2011-11-04
        • 2018-09-14
        相关资源
        最近更新 更多