setTimeout() 输出一个非预期的 number/timer

setTimeout() outputs a non expected number/timer

我正在尝试调用我的 Action.js 中的动作创建者以在 3000 毫秒后使用 setTimeout() 删除警报,并在最后输出 number/timer 61消息。

如何删除这个 61

输出:

Password too short (min 6 characs.)61

代码:

const Alert = props => {
  return (
    <div>
      {props.alert && (
        <div className={`alert alert-${props.alert.type}`}>
          <i className="fas fa-info-circle"> {props.alert.msg}</i>
          {setTimeout(() => props.removeAlert(), 3000)}
        </div>
      )}
    </div>
  );
};

谢谢。

您应该像这样正确构建代码:

const setAlert = props => 
{ 
  if(props.alert){
    setTimeout(() => props.removeAlert(), 3000)
    return (props.alert.msg); 
  }
};

如果它只是行动并且不会为您产生任何价值,请不要将所有内容都放在 return 声明下

我强烈建议您阅读 Robert C. Martin 的书 'Clean Code'

希望对您有所帮助:

尝试在您的组件中分离关注点,在这种情况下渲染和设置超时:

您使用的是什么版本的 React? 如果你有更高的 16.8 Hooks 运行 每次渲染后,包括第一个这样:你可以尝试这样的事情:

import React, { useEffect } from 'react';

useEffect(() => {
    // Run your setTimeout here!!!

  });

return (
  // Render your component
);

或者,如果您使用的是较低版本的 React,您可以将组件转换为 class 组件,而不是在渲染方法中调用 setTimeout,而是在 componentDidMount()

class Alert extends React.Component { 
  constructor(props){
    super(props)
  }

  componentDidMount() {
    setTimeout(() => this.props.removeAlert(), 3000)
  }

  render() {
    return (
     // Set your conditions &&
     // Render your message or component
   );
  }
}