我得到这个警告在反应:

index.js:1 Warning: Cannot update a component (`ConnectFunction`) 
while rendering a different component (`Register`). To locate the 
bad setState() call inside `Register` 

我去了堆栈跟踪中指出的位置,并删除了所有设置状态,但警告仍然存在。这可能发生在redux调度?

我的代码:

register.js

class Register extends Component {
  render() {
    if( this.props.registerStatus === SUCCESS) { 
      // Reset register status to allow return to register page
      this.props.dispatch( resetRegisterStatus())  # THIS IS THE LINE THAT CAUSES THE ERROR ACCORDING TO THE STACK TRACE
      return <Redirect push to = {HOME}/>
    }
    return (
      <div style = {{paddingTop: "180px", background: 'radial-gradient(circle, rgba(106,103,103,1) 0%, rgba(36,36,36,1) 100%)', height: "100vh"}}>
        <RegistrationForm/>
      </div>
    );
  }
}

function mapStateToProps( state ) {
  return {
    registerStatus: state.userReducer.registerStatus
  }
}

export default connect ( mapStateToProps ) ( Register );

函数,该函数触发了由register.js调用的registerForm组件中的警告

handleSubmit = async () => {
    if( this.isValidForm() ) { 
      const details = {
        "username": this.state.username,
        "password": this.state.password,
        "email": this.state.email,
        "clearance": this.state.clearance
      }
      await this.props.dispatch( register(details) )
      if( this.props.registerStatus !== SUCCESS && this.mounted ) {
        this.setState( {errorMsg: this.props.registerError})
        this.handleShowError()
      }
    }
    else {
      if( this.mounted ) {
        this.setState( {errorMsg: "Error - registration credentials are invalid!"} )
        this.handleShowError()
      }
    }
  }

堆栈跟踪:


当前回答

使用上面的一些答案,我摆脱了以下错误:

from

if (value === "newest") {
  dispatch(sortArticlesNewest());
} else {
  dispatch(sortArticlesOldest());
}

这段代码位于我的组件顶层

to

    const SelectSorting = () => {
  const dispatch = useAppDispatch();

  const {value, onChange} = useSelect();

  useEffect(() => {
    if (value === "newest") {
      dispatch(sortArticlesNewest());
    } else {
      dispatch(sortArticlesOldest());
    }
  }, [dispatch, value]);

其他回答

我的案例是使用setState回调,而不是setState + useEffect

坏❌

  const closePopover = useCallback(
    () =>
      setOpen((prevOpen) => {
        prevOpen && onOpenChange(false);
        return false;
      }),
    [onOpenChange]
  );

好✅

  const closePopover = useCallback(() => setOpen(false), []);

  useEffect(() => onOpenChange(isOpen), [isOpen, onOpenChange]);

此警告从React V16.3.0开始引入。

如果您正在使用功能组件,您可以将setState调用包装到useEffect中。

不能工作的代码:

const HomePage = (props) => {
    
  props.setAuthenticated(true);

  const handleChange = (e) => {
    props.setSearchTerm(e.target.value.toLowerCase());
  };

  return (
    <div key={props.restInfo.storeId} className="container-fluid">
      <ProductList searchResults={props.searchResults} />
    </div>
  );
};

现在你可以把它改成:

const HomePage = (props) => {
  // trigger on component mount
  useEffect(() => {
    props.setAuthenticated(true);
  }, []);

  const handleChange = (e) => {
    props.setSearchTerm(e.target.value.toLowerCase());
  };

  return (
    <div key={props.restInfo.storeId} className="container-fluid">
      <ProductList searchResults={props.searchResults} />
    </div>
  );
};

使用上面的一些答案,我摆脱了以下错误:

from

if (value === "newest") {
  dispatch(sortArticlesNewest());
} else {
  dispatch(sortArticlesOldest());
}

这段代码位于我的组件顶层

to

    const SelectSorting = () => {
  const dispatch = useAppDispatch();

  const {value, onChange} = useSelect();

  useEffect(() => {
    if (value === "newest") {
      dispatch(sortArticlesNewest());
    } else {
      dispatch(sortArticlesOldest());
    }
  }, [dispatch, value]);

当我愚蠢地调用调用调度的函数,而不是传递一个引用给按钮上的onClick时,我得到了这个。

  const quantityChangeHandler = (direction) => {
    dispatch(cartActions.changeItemQuantity({title, quantityChange: direction}));
  }
...
          <button onClick={() => quantityChangeHandler(-1)}>-</button>
          <button onClick={() => quantityChangeHandler(1)}>+</button>

一开始,我直接打电话给你,没有那个大箭头包装。

我认为这很重要。 @Red-Baron在这篇文章中指出:

@machineghost:我认为你误解了这条信息警告的内容。

将更新父节点状态的回调传递给子节点并没有什么错。这一直都很好。

问题是当一个组件在另一个组件中排队更新时,而第一个组件正在呈现。

换句话说,不要这样做:

function SomeChildComponent(props) {
    props.updateSomething();
    return <div />
}

但这是可以的:

function SomeChildComponent(props) {
    // or make a callback click handler and call it in there
    return <button onClick={props.updateSomething}>Click Me</button>
}

而且,正如Dan多次指出的那样,在渲染时在同一个组件中排队更新也很好:

function SomeChildComponent(props) {
  const [number, setNumber] = useState(0);

  if(props.someValue > 10 && number < 5) {
    // queue an update while rendering, equivalent to getDerivedStateFromProps
    setNumber(42);
  }

  return <div>{number}</div>
}