Reactjs事件/操作按钮未按预期切换。
正在尝试添加关注和取消关注操作按钮。当我通过“关注”按钮通过 axios 发布信息时, 它将数据发布到服务器后端并返回成功消息。然后,“跟随”按钮切换为“取消关注”按钮。
现在我的问题是,当用户尝试取消关注某人时,“取消关注”按钮没有切换回“关注按钮”。
请我在这里做错什么了。
这是json成功消息
[{"status":"success", "follow":"1", "unfollow":"0"}]
这是我的代码
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import axios from 'axios';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
result_data: '',
data: [],
loading: false
};
}
componentDidMount() {
this.setState({
data: [{"uid":"1","name":"Nancy"},{"uid":"2","name":"Moore"}],
});
}
// update user following
handleFollowUser(user_id) {
const uid_data = { user_id: user_id };
axios
.get("http://localhost/data.json", { uid_data })
.then(response => {
this.setState(state => ({
//data: newData,
result_data: response.data[0].status
}));
alert(result_data);
})
.catch(error => {
console.log(error);
});
}
// update user unfollowing
handleUnFollowUser(user_id) {
const uid_data = { user_id: user_id };
axios
.get("http://localhost/data.json", { uid_data })
.then(response => {
this.setState(state => ({
//data: newData,
result_data: response.data[0].status
}));
alert(result_data);
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<span>
<label>
<ul>
<h1>Users</h1> <br />
{this.state.result_data }
{this.state.data.map((users) => {
return (
<div key={users.uid}>
<div>
<b> Name: </b>{users.name}
<br />
{this.state.result_data === ''
? <span onClick={() =>
this.handleFollowUser(users.uid)}>Follow</span>
: <span onClick={() =>
this.handleUnFollowUser(users.uid)}>unfollow</span>
}
</div>
</div>
)
}
)}
</ul>
</label>
</span>
);
}
}
答案 0 :(得分:0)
这就是解决我的Reactjs 问题的方法。我首先进行初始化
isToggleOn: !state.isToggleOn
在click事件和我实现的构造函数中
this.state = {isToggleOn: true};
我的点击按钮变为
<button onClick={this.handleFollowUser}>
{this.state.isToggleOn ? 'Follow' : 'Unfollow'}
</button>