【问题标题】:Unable to render output of an API call made from a text field unto the UI无法将从文本字段发出的 API 调用的输出呈现到 UI
【发布时间】:2020-12-12 10:44:12
【问题描述】:

请目前正在使用代码沙箱上的反应构建一个简单的用户界面。我只希望用户能够在文本字段中输入 API 端点并将输出(响应数据)呈现在文本区域上。下面是我的代码沙盒项目链接: https://codesandbox.io/s/dry-surf-6ygc5?file=/src/components/PostList.jsx。我们将非常感谢您的意见!

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您似乎错过了输入的 OnChange 事件中输入文本的目标值。如果有帮助,请查看下面的代码。

     <input
                name="inputApi"
                onChange={(e) => this.setState({ apiText: e.target.value })}
                type="text"
              />
    

    我删除了您的一些代码。我也没有做其他功能,比如错误处理。请将 try catch 块添加到 Async

    submitHandler = async (e) => {
            e.preventDefault();
            try {
              const resp = await axios.get(
                `https://jsonplaceholder.typicode.com/${this.state.apiText}`
              );
              // console.log(resp.data);
        
              this.setState({ posts: resp.data });
            } catch (error) {
              this.setState({ errorMsg: error.message });
            }
          };
    

    完整代码如下。

    import React, { Component } from "react";
    import axios from "axios"; //for making API calls
    
    class PostList extends Component {
      constructor(props) {
        super(props);
    
        /**
         * the lines below are unneccessary
         * as the functions are arrow functions
         * and require no binding
         * value={this.state.api}
         */
    
        this.state = {
          posts: [],
          errorMsg: "",
          api: {},
          apiText: ""
        };
      } //end of constructor
    
      submitHandler = async (e) => {
        e.preventDefault();
        try {
          const resp = await axios.get(
            `https://jsonplaceholder.typicode.com/${this.state.apiText}`
          );
          // console.log(resp.data);
    
          this.setState({ posts: resp.data });
        } catch (error) {
          this.setState({ errorMsg: error.message });
        }
      };
    
      render() {
        const { posts, errorMsg } = this.state; //destructure the state object
        //console.log(res.data);
        return (
          <div>
            <form onSubmit={this.submitHandler}>
              <input
                name="inputApi"
                onChange={(e) => this.setState({ apiText: e.target.value })}
                type="text"
              />
              <input type="submit" />
            </form>
            List of Posts: {posts.length}
            {posts.length ? (
              <div>
                <textarea value={this.state.posts[0].title} readOnly />
              </div>
            ) : null}
            {errorMsg ? <div>{errorMsg}</div> : null}
          </div>
        ); //endOfReturn
      } //endOfRender
    } //endOfPostList
    export default PostList;
    
    /**posts.map((post) => <div key={post.id}>{post.title}</div>)*/
    

    【讨论】:

    • 感谢 Praga 的意见。我很感激
    【解决方案2】:

    您在获取submitHandler 中的值时遇到了一个小错误。

    您传递的是字符串"e.target.value",而不是用户输入的值,这是不正确的。

    const resp = axios.get("e.target.value");
    

    改为这样使用

    const inputLink = e.target[0].value;
    const resp = axios.get(inputLink);
    

    将调用axios.get函数的结果存储在组件state中也是没有意义的。 调用后立即可以使用 then 并捕获调用 axios.get 的结果

    axios
        .get(inputLink)
        .then((res) => {
            this.setState({ posts: res.data });
        })
        .catch((error) => {
            this.setState({
                errorMsg: "error retrieving data"
            });
        });
    

    因此,最小的工作组件将类似于 this

    【讨论】:

    • 非常感谢 xom9ikk。我只需要稍微澄清一下 e.target[0].value 就是说 e.target 是一个数组?
    • @Abelinho 当您提交表单时,您会在handler 中获得一个event。这个event 有一个target 字段。这是包含表单中所有对inputs 的引用的数组。但是在 React 中不推荐这种方法。最好使用受控组件reactjs.org/docs/forms.html#controlled-components。在示例中,我没有修复它,以免让您更加困惑)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2013-01-21
    相关资源
    最近更新 更多