Meine Lösung mit Redux (und redux-actions
) ...
Aktion:
export const setToaster = createAction('SET_TOASTER');
Reducer:
const initialState = {
toaster: {
message: ''
}
};
function reducer(state = initialState, action) {
switch(action.type) {
case 'SET_TOASTER':
return {
...state,
toaster: { ...state.toaster, ...action.payload }
};
};
}
Toaster Komponente:
// not showing imports here...
class MyToaster extends Component {
constructor(props) {
super(props);
this.state = {
// set default toaster props here like intent, position, etc.
// or pass them in as props from redux state
message: '',
show: false
};
}
componentDidMount() {
this.toaster = Toaster.create(this.state);
}
componentWillReceiveProps(nextProps) {
// if we receive a new message prop
// and the toaster isn't visible then show it
if (nextProps.message && !this.state.show) {
this.setState({ show: true });
}
}
componentDidUpdate() {
if (this.state.show) {
this.showToaster();
}
}
resetToaster =() => {
this.setState({ show: false });
// call redux action to set message to empty
this.props.setToaster({ message: '' });
}
showToaster =() => {
const options = { ...this.state, ...this.props };
if (this.toaster) {
this.resetToaster();
this.toaster.show(options);
}
}
render() {
// this component never renders anything
return null;
}
}
App Komponente:
oder was auch immer Ihre Root-Level-Komponente ...
const App = (props) =>
<div>
<MyToaster {...props.toaster} setToaster={props.actions.setToaster} />
</div>
Einige Andere Komponenten:
Wo Sie den Toaster aufrufen müssen ...
class MyOtherComponent extends Component {
handleSomething =() => {
// We need to show a toaster!
this.props.actions.setToaster({
message: 'Hello World!'
});
}
render() { ... }
}
Ich habe das gleiche Problem. Ich löste Mytoaster.show teilweise in der render-Methode mit einem if-Steuerelement. Ich benutze Redux, und wenn mein Fehler Requisiten verändert, rende ich Mytoaster.show, sonst null. Jetzt ist mein Problem Feuer eine Aktion auf Entlassung .. – Arcy