首页 > 解决方案 > 如何在 React js 中将字符串附加到 API url onclick

问题描述

当我点击一个按钮时,我想在所有 url 中附加一个字符串,该怎么做?

这是代码 App.js

import React, { Component } from "react";
import Button from './Button';

let API = 'https://someurl.com/';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      results: []
    };
    this.updateUrl = this.updateUrl.bind(this);
  }

  componentWillMount = () => {
    this.fetchData();
  }

  fetchData = async () => {
    const response = await fetch(API);
    const json = await response.json();
    this.setState({ 
      results: json.results 
    });
  };


  updateButton = (event) => {
     this.setState({ 
      API.concat('?format=fzjeozfij')
    });
  }

  render() {
    return (
      <div>
        <Button data={this.state} />
      </div>
    );
  }
}

export default App;

按钮.js

import React, { Component } from 'react';

class Button extends Component {
  render() {
    const updateButton = this.props.data;
    return (
      <button type="button" onClick={updateButton}>Button</button>
    )
  }
}

export default Button;

我的目标是从https://someurl.com/?format=zegizhgzconst API获取url 我想我必须修改 fetchData 函数以将一些字符串连接到 url 但我不知道该怎么做

标签: reactjs

解决方案


  updateButton = () => {
  const nApi = `${this.state.api}?format=wookiee`;
this.setState({ api: nApi });

  this.fetchData(nApi);
      }
    render() {
        return (
          <div>
            <Button onClick={this.updateButton}/>
          </div>
        );
      }

     fetchData = async (api) => {
        const response = await fetch(api);
        const json = await response.json();
        this.setState({ 
          results: json.results 
        });
      };

按钮.jsx

import React, { Component } from 'react';

class Button extends Component {
  render() {
    const {onClick} = this.props;
    return (
      <button type="button" onClick={onClick}>Button</button>
    )
  }
}

推荐阅读