向我的React应用获取API请求

时间:2018-07-18 10:56:52

标签: javascript reactjs rest api react-native

我试图调用一个API来在React.js中显示我的网站上的信息,该API需要读取令牌,但是我不知道生成令牌需要做什么,因为我的应用程序不需要任何注册或登录。就像产品目录一样,您可以个性化它们。我不太了解这一点,因为我是新手,而且我自己都在学习,所以对不起,如果对此感到困惑,请随时提出任何问题,我会尽力回答:)

这是到目前为止我拥有的代码:

export class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      models: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(myUrlAPI)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          models: json
        });
      });
  }

  render() {
    const { isLoaded, models } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>
          <ul>{models.map(model => <li>{model.name}</li>)};</ul>

          <a href="/sofa">
            <div className="Parcelas">
              <img
                src="../../img/image-card-1@2x.png"
                className="ParcImage"
                alt="sofa"
              />
              <h1>Sofa hipnos</h1>
              <h2>
                1,200<span>€</span>
              </h2>
              <p className="Features">
                w 20.5 x 15.5 x h 19.5 (cm)<br />Pele
              </p>

              <button className="Botao">
                <p className="MostraDepois">See Details</p>
                <span>+</span>
              </button>
              <img
                src="../../img/points.svg"
                className="Decoration"
                alt="points"
              />
            </div>
          </a>
        </div>
      );
    }
  }
}

<ul>标签中,我只是想测试 json 的结果。

此外,每次我使用.map进行数组处理时,都会出现此错误(TypeError: models.map is not a function)或类似错误,您能告诉我为什么吗?

1 个答案:

答案 0 :(得分:1)

尝试这种方式,对于令牌,您需要与后端开发人员确认发送方式和内容。

 let token = '1234567'; 
    fetch(myUrlAPI, {
      method: "GET",
      headers: {
        "authorization-key": token
      }
    }).then(res => res.json()
    ).then(function(json) {
      this.setState({
          isLoaded: true,
          models: json
        });
    }, function(error) {
      console.log(error)
    })
相关问题