仅在切换按钮打开时显示 state.joke
Display state.joke when toggle button is only ON
我正在努力使笑话仅在切换按钮为 'ON' 时显示。现在我一直在显示这个笑话,但不确定我应该从这里去哪里。我应该使用 useEffect 吗?如何使用?
import React from 'react';
import axios from "axios";
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.jokes = "https://icanhazdadjoke.com/"
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
async componentDidMount() {
const url = "https://icanhazdadjoke.com/"
let result = null;
try {
result = await axios.get(url, {
headers: {
Accept: "application/json"
}
})
} catch(e) {
console.log(e);
}
this.setState({jokes: result.data.joke});
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
<p>
> This displays the joke and changes when page is refreashed
{this.state.jokes}
</p>
</div>
);
}
}
export default Toggle;
你可以这样做:
{this.state.isToggleOn && <p> {this.state.jokes} </p>
它只在切换打开时显示笑话。
我正在努力使笑话仅在切换按钮为 'ON' 时显示。现在我一直在显示这个笑话,但不确定我应该从这里去哪里。我应该使用 useEffect 吗?如何使用?
import React from 'react';
import axios from "axios";
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.jokes = "https://icanhazdadjoke.com/"
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
async componentDidMount() {
const url = "https://icanhazdadjoke.com/"
let result = null;
try {
result = await axios.get(url, {
headers: {
Accept: "application/json"
}
})
} catch(e) {
console.log(e);
}
this.setState({jokes: result.data.joke});
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
<p>
> This displays the joke and changes when page is refreashed
{this.state.jokes}
</p>
</div>
);
}
}
export default Toggle;
你可以这样做:
{this.state.isToggleOn && <p> {this.state.jokes} </p>
它只在切换打开时显示笑话。