我想在单击按钮时将字符串附加到所有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;
Button.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;
我的目标是将网址从const API
到https://someurl.com/?format=zegizhgz
我想我必须修改fetchData函数以将一些字符串连接到url,但是我不确定如何做到这一点
答案 0 :(得分:0)
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
});
};
Button.jsx
import React, { Component } from 'react';
class Button extends Component {
render() {
const {onClick} = this.props;
return (
<button type="button" onClick={onClick}>Button</button>
)
}
}