Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 无法将从文本字段发出的API调用的输出呈现给UI_Reactjs - Fatal编程技术网

Reactjs 无法将从文本字段发出的API调用的输出呈现给UI

Reactjs 无法将从文本字段发出的API调用的输出呈现给UI,reactjs,Reactjs,我目前正在使用react on codesandbox构建一个简单的UI。我只希望用户能够在文本字段中输入API端点,并在文本区域中呈现输出(响应数据)。下面是我的codesandbox项目链接: . 我们将非常感谢您的意见 在输入的OnChange事件中,您似乎没有达到输入文本的目标值。如果有帮助,请参阅下面的代码 <input name="inputApi" onChange={(e) => this.setS

我目前正在使用react on codesandbox构建一个简单的UI。我只希望用户能够在文本字段中输入API端点,并在文本区域中呈现输出(响应数据)。下面是我的codesandbox项目链接:
. 我们将非常感谢您的意见

在输入的OnChange事件中,您似乎没有达到输入文本的目标值。如果有帮助,请参阅下面的代码

 <input
            name="inputApi"
            onChange={(e) => this.setState({ apiText: e.target.value })}
            type="text"
          />
完整代码如下

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>)*/
import React,{Component}来自“React”;
从“axios”导入axios//用于进行API调用
类PostList扩展组件{
建造师(道具){
超级(道具);
/**
*下面的几行是不必要的
*因为函数是箭头函数
*不需要约束
*值={this.state.api}
*/
此.state={
员额:[],
errorMsg:“,
api:{},
apiText:“
};
}//构造函数的结尾
submitHandler=异步(e)=>{
e、 预防默认值();
试一试{
const resp=等待axios.get(
`https://jsonplaceholder.typicode.com/${this.state.apiText}`
);
//控制台日志(相应数据);
this.setState({posts:resp.data});
}捕获(错误){
this.setState({errorMsg:error.message});
}
};
render(){
const{posts,errorMsg}=this.state;//解构state对象
//console.log(res.data);
返回(
this.setState({apiText:e.target.value})
type=“text”
/>
帖子列表:{Posts.length}
{posts.length(
):null}
{errorMsg?{errorMsg}:null}
);//内胎
}//endOfRender
}//endOfPostList
导出默认的PostList;
/**posts.map((post)=>{post.title})*/

获取
提交程序中的值时出现一个小错误

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

const resp=axios.get(“e.target.value”);
像这样使用它

const inputLink=e.target[0]。值;
const resp=axios.get(inputLink);
在组件
状态中存储调用
axios.get
函数的结果也没有意义。 通话结束后,您可以立即使用then并获取调用axios.get的结果

axios
.get(输入链接)
。然后((res)=>{
this.setState({posts:res.data});
})
.catch((错误)=>{
这是我的国家({
errorMsg:“检索数据时出错”
});
});

因此,最小的工作组件看起来像。

感谢Praga的输入。我非常欣赏银行。我只需要对e.target[0]进行一点澄清。值是说e.target是一个数组吗?@Abelinho提交表单时,在
处理程序中会得到一个
事件
。此
事件
有一个
目标
字段。这是一个数组,其中包含对表单中
input
s的所有引用。但React中不建议使用此方法。最好使用受控组件。在本例中,我没有修复它,以免使您更加困惑)
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>)*/