有沒有辦法像mobx一樣做這樣的事情?將this.props.prop和nextProps.prop與mobx比較
componentWillUpdate(nextProps) {
if (this.props.prop !== nextProps.prop) {
/* side effect, ex. router transition */
}
}
從我的經驗,this.props.prop
總是等於nextProps.prop
即使在componentWill-
鉤...
UPD這裏有更具體的用例 - 簡單的登錄場景:
商店
class AppStore {
@observable viewer = new ViewerStore();
}
class ViewerStore {
@observable id;
@observable name;
@observable error;
fromJSON(json = {}) {
this.id = json.id;
this.name = json.name;
}
clearError() {
this.error = null;
}
login({ email, password }) {
fetch('/login', {
method: 'POST',
body: JSON.stringify({
email,
password
}),
credentials: 'same-origin'
})
.then(json => {
this.fromJSON(json);
})
.catch(({ error }) => {
this.error = error;
})
}
}
陣營部分
class LogInPage extends Component {
componentWillUpdate(nextProps) {
if (nextProps.viewer.id && !this.props.viewer.id) {
this.props.viewer.clearError();
this.props.onSuccess();
}
}
login = e => {
e.preventDefault();
this.props.viewer.login({
email: e.target.elements['email'].value,
password: e.target.elements['password'].value,
});
}
render() {
return (
<div>
<h1>Log In</h1>
<form onSuccess={this.login}>
<input type="text" name="email" />
<input type="password" name="password" />
<input type="submit" />
</form>
{ this.props.viewer.error && (
<div>
<b>Error</b>: {this.props.viewer.error}
</div>
)}
</div>
);
}
}
const store = new AppStore();
ReactDOM.render(<LogInPage
viewer={store.viewer}
onSuccess={() => alert("Hello!")}
/>
, container);
所以基本上,我只是希望能夠做一些事情,當觀衆從undefined
id
開關的東西
你能描述一下爲什麼路線必須改變,爲什麼這必須是由接收全倉組件中的責任?例如,我希望這種情況發生在收到特定物品的商店中。也許分享一些代碼? – mweststrate