1 回答

TA貢獻2011條經驗 獲得超2個贊
這是一個簡化的示例,但它應該為您提供有關如何根據用戶角色有條件地獲取和呈現數據的基本概念。
前端調用API端點AUTH數據(
userId
以及token
在此實例中)后端根據身份驗證數據確定角色,返回與此角色相關的數據(例如,
phone
如果他們的角色允許,則包括)前端呈現響應數據(例如,
"Hidden"
如果phone
不存在則呈現)
以下是您的React
組件的外觀:
class CustomerList extends Component {
constructor(props) {
super(props);
this.state = {
customers: []
};
}
componentDidMount() {
// fetch list data
fetch('https://myapi.com/api/getCustomers', {userId: 12345, token: someToken})
.then(res => res.json())
.then(response => {
this.setState({customers: response.customers});
});
}
render() {
const { customers } = this.state;
return (
<div className="customers">
{customers.length &&
<ul>
{customers.map(customer => (
<li>
<div className="name">
Name: {customer.name}
</div>
<div className="phone">
Phone: {customer.phone || "Hidden"}
</div>
</li>
))}
</ul>
}
{!customers.length &&
<div>Loading...</div>
}
</div>
);
}
}
角色只是一種建議。您可以在后端通過其他方式確定當前用戶有權查看哪些數據。關鍵是你返回給前端的數據應該只包含用戶有權查看的數據。您不應該返回所有數據,然后在前端有條件地呈現它。
添加回答
舉報