reactjs - 如何在 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 但我不知道该怎么做
解决方案
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>
)
}
}
推荐阅读
- swift - 一个 Viewcontroller 中有两个 Tableview 的“索引超出范围”错误
- java - JavaFx:自动完成多选文本字段
- tensorflow - TF 2.0 Beta:如何重新初始化定制模型的权重?
- c++ - __gcd 的时间复杂度是多少?
- python - Python 3.x 中的机会游戏?
- xamarin.forms - 选择器按钮的颜色在 android 5.1 上没有改变
- angular - Angular 前端未从端点加载:请求了不安全的 XMLHttpRequest 端点
- apache-spark - 将列表列表转换为 Spark Dataframe
- javascript - 如何在多选中选择剩余元素
- dart - 从参数类型推断类型