Reactjs中的超时

Timeouts in Reactjs?

本文关键字:超时 Reactjs      更新时间:2023-09-26

我正在为我的网站建立一个通知组件。当你点击"添加"按钮项目就被添加了在我的网站顶部会出现一个绿色的提示栏显示"创建成功"

现在一秒钟后,我希望它消失。我不确定做这件事的最好方法是什么?它是有一个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;
}

通常我会使用像growl这样的东西,但我没有看到任何reactjs(我确实看到了一些,但似乎都不是很流行)

因为它看起来像你在使用redux-thunk,我会在你的动作创建器中设置一个超时来触发另一个动作来关闭通知,例如

import {actions}  from './Actions.js';
export function setNotifer(success) {
    return function (dispatch) {
        dispatch({ type: actions.SET_NOTIFIER, payload: success });
        setTimeout(() => dispatch({ type: actions.CLOSE_NOTIFIER }), 1000) 
    };
}

那么当你的减速机接收到CLOSE_NOTIFIER动作时,它就会取消成功和错误属性。

这将使您的组件保持同步,它最终是在redux中发出ajax请求时常用的相同模式。

您可以使用一个简单的setTimeout来实现这一点:

(*edit*我已经更新了代码片段以使用reduxredux-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')
);
.message {
  border: 1px solid green;
  background-color: rgba(0,255,0, 0.1);
  border-radius: 4px;
}
<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>