是否可以从使用 axios 发回 json 响应的端点获取 <options> 的值?

Is it possible to get values for <options> from an endpoint that sends back json response using axios?

所以,我有这个端点:http://127.0.0.1:8000/api/materials 那会 return 这个 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 请求,以便我可以获得我需要的标题?

首先,向您的状态添加一个 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>
    )
}

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

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

componentDidMount() {
  this.materialList();
}

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

我假设您 post 的 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>);
    }
}

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

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