我正在为我的网站构建一个notifer组件。基本上你打了一个说"添加"并且该项目已添加"在我的网站顶部会出现一个绿色栏,并说“成功创建了#34;
”现在一秒钟之后,我希望它消失。我不确定最好的办法是什么?在某个地方有一个javascript计时器吗?
import React from 'react';
import 'materialize-css/sass/materialize.scss';
import 'font-awesome/scss/font-awesome.scss';
import 'materialize-css/js/materialize.js';
import classNames from 'classnames/index.js';
export default class Notifer extends React.Component {
render() {
var notifcationClasses = classNames({
'notifcation-success': this.props.notiferReducer.success,
'notifcation-error': this.props.notiferReducer.error,
'hide': !(this.props.notiferReducer.success || this.props.notiferReducer.error)
});
return (
<div id="notifcation" className={notifcationClasses}>
Sucessfully created
</div>
);
}
}
动作
import {actions} from './Actions.js';
export function setNotifer(success) {
return function (dispatch) {
dispatch({ type: actions.SET_NOTIFIER, payload: success });
};
}
减速
import { actions } from '../actions/Actions';
export default function NotiferReducer(state = {
success: false,
error: false
}, action) {
switch (action.type) {
case actions.SET_NOTIFIER: {
return {
success: action.payload,
error: !action.payload
};
}
}
return state;
}
通常情况下我会使用像咆哮这样的东西,但我没有看到反应的任何东西(我确实看到了一些,但它们似乎都不是很受欢迎)
答案 0 :(得分:1)
您可以使用简单的setTimeout
来实现此目的:
(*编辑*我已将代码段更新为使用redux
和redux-thunk
)
const { Component } = React;
const { render } = ReactDOM;
const { createStore, combineReducers, applyMiddleware } = Redux;
const { connect, Provider } = ReactRedux;
const message = (state = null, action) => {
switch (action.type) {
case 'SET_NOTIFICATION':
return action.message;
default:
return state;
}
};
const setNotification = (message, duration) => (dispatch, getState) => {
dispatch({type: 'SET_NOTIFICATION', message: message});
setTimeout(() => {
dispatch({type: 'SET_NOTIFICATION', message: null});
}, duration);
};
const store = createStore(
combineReducers({message: message}),
applyMiddleware(ReduxThunk.default)
);
class App extends Component {
showMessage = () => {
this.props.dispatch(
setNotification('This message will self destruct in 3 seconds', 3000)
);
};
render() {
return (
<div>
{this.props.message && <div className="message">{this.props.message}</div>}
<br />
<button onClick={this.showMessage}>Click to show message</button>
</div>
);
}
}
App = connect(
state => ({ message: state.message })
)(App);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
&#13;
.message {
border: 1px solid green;
background-color: rgba(0,255,0, 0.1);
border-radius: 4px;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://npmcdn.com/redux@3.5.2/dist/redux.min.js"></script>
<script src="https://npmcdn.com/redux-thunk@2.1.0/dist/redux-thunk.min.js"></script>
<script src="https://npmcdn.com/react-redux@4.4.5/dist/react-redux.min.js"></script>
<div id="app"></div>
&#13;