2 回答

TA貢獻(xiàn)2021條經(jīng)驗 獲得超8個贊
有沒有更好(更多反應(yīng))的方式來觸發(fā)渲染功能......
通常的方法是擁有狀態(tài),在這種情況下,至少是用戶是否登錄的布爾值,并在用戶成功登錄或注銷時更新該狀態(tài)。更新狀態(tài)會觸發(fā)渲染。
就您而言,由于您使用的是 Redux,因此您的狀態(tài)可能會在那里。
我不使用 Redux(還沒有?),這大概是沒有的樣子,粗略地(如果您使用的是類組件,就像您看起來的那樣):
class App extends Component {
constructor(props) {
super(props);
this.state = {
loggedIn: /*...initial value, perhaps from web storage or cookie...*/;
};
this.onLogin = this.onLogin.bind(this);
this.onLogout = this.onLogout.bind(this);
}
onLogin() {
// ...probably stuff here, then:
this.setState({loggedIn: true});
}
onLogout() {
// ...probably stuff here, then:
this.setState({loggedIn: false});
}
render() {
if (this.state.logedIn) {
return <AppComponent onLogout={this.onLogout}/>;
}
return <Login onLogin={this.onLogin}/>;
}
}
或帶鉤子:
const App = () => {
const [loggedIn, setLoggedIn] = useState(/*...initial value, perhaps from web storage or cookie...*/);
const onLogin = useCallback(() => {
// ...probably stuff here, then:
setLoggedIn(true);
}, [loggedIn]);
const onLogout = useCallback(() => {
// ...probably stuff here, then:
setLoggedIn(false);
}, [loggedIn]);
if (this.state.logedIn) {
return <AppComponent onLogout={onLogout}/>;
}
return <Login onLogin={onLogin}/>;
}
(再次,粗略)

TA貢獻(xiàn)1921條經(jīng)驗 獲得超9個贊
如果您需要更新組件狀態(tài),那么您可以傳遞一個 observable 并監(jiān)聽更改或使用一些狀態(tài)管理庫。
這是一種可能的解決方案:
創(chuàng)建可觀察的類
declare type IObserverHandler = (event: any) => void;
export class Observable {
private observers: IObserverHandler[] = [];
public subscribe(observer: IObserverHandler) {
if (!this.observers.includes(observer)) {
this.observers.push(observer);
}
}
public unsubscribe(observer: IObserverHandler) {
this.observers = this.observers.filter(o => o !== observer);
}
public publish(event: any) {
for (const observer of this.observers) {
observer(event);
}
}
}
創(chuàng)建 Login 類,該類將發(fā)布有關(guān)登錄或注銷等操作的事件
class Login extends Observable {
public login() {
this.publish({ value: true });
}
public logout() {
this.publish({ value: false });
}
}
在組件中訂閱觀察者并使用事件值更新組件狀態(tài)
export abstract class Component extends React.Component<any, any> {
private observer: IObserverHandler;
private observable: Login;
constructor(props: any) {
super(props);
this.observable = this.props.observable;
this.state = { isAuthenticated: false }
this.observer = (event) => {
this.setState({ isAuthenticated: event.value })
}
this.observable.subscribe(this.observer);
}
componentWillUnmount() {
this.observable.unsubscribe(this.observer);
}
}
添加回答
舉報