我與終極版(和redux-actions
)解決方案...
操作:
export const setToaster = createAction('SET_TOASTER');
減速機:
const initialState = {
toaster: {
message: ''
}
};
function reducer(state = initialState, action) {
switch(action.type) {
case 'SET_TOASTER':
return {
...state,
toaster: { ...state.toaster, ...action.payload }
};
};
}
多士爐組件:
// 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;
}
}
應用組件:
或任何你的根級組件...
const App = (props) =>
<div>
<MyToaster {...props.toaster} setToaster={props.actions.setToaster} />
</div>
一些其他部件:
,你需要調用烤麪包機......
class MyOtherComponent extends Component {
handleSomething =() => {
// We need to show a toaster!
this.props.actions.setToaster({
message: 'Hello World!'
});
}
render() { ... }
}
我有同樣的問題。我用一個if控件部分解決了Mytoaster.show在渲染方法中的問題。我使用Redux,當我的錯誤道具改變時,我渲染Mytoaster.show,否則爲null。現在我的問題是解僱一個行動.. – Arcy