简体   繁体   English

如果插入到字符串中,则 React 状态更新不会反映在子组件中

[英]React State update doesn't get reflected inside a child component if interpolated into a string

I've got a problem where my component re-renders successfully but the state doesn't change inside the child components that receives the date interpolated inside a string我遇到了一个问题,我的组件重新渲染成功,但在接收插入字符串内的日期的子组件内状态没有改变

Example:例子:

export const IntegrationPage = () => {

  const currentWorkspace = useSelector(getCurrentWorkspace);
  const workspaceState = useSelector(getWorkspaceState);

  const [workspaceId, setWorkspaceId] = useState(currentWorkspace?.identifier);

  useEffect(() => {
    setWorkspaceId(currentWorkspace?.identifier);
//if I console.log workspaceId here, it updates correctly as well.
  }, [currentWorkspace]);

  if (!currentWorkspace || workspaceState.status === Status.requesting || !workspaceId) {
    return <LoadingSpinner />;
  }
  return (
    <div className={styles.IntegrationPage}>
      <div className={styles.content}>
        <div className={styles.left}>
                                                           //This updates correctly
          <Card leftHeader="Tracking overview" rightHeader={`ID: ${workspaceId}`}>
            <CardItem content="No visits in last 48 hours" header="No data" variant="item" />
          </Card>
            <CodeBox>
             {`something here ${workspaceId} something else`}
            </CodeBox>
            ...
        </div> 
    </div>
  );
};

CodeBox:代码框:


type CodeBoxProps = {
  children?: ReactNode;
  src?: string;
};

export const CodeBox: FunctionComponent<CodeBoxProps> = ({ children, src }) => {
  const dispatch = useDispatch();
  const handleCopy = () => {
    const text = src?.toString() ?? children?.toString();
    navigator.clipboard.writeText(text ? text : "");
    dispatch(showNotification("Code was copied to clipboard", "success", "clipboard", 2250));
  };

  return (
    <div className={styles.codeBox} onClick={handleCopy}>
      <code className={styles.code}>{src ?? children}</code>
    </div>
  );
};

As you can see, I've tried passing the code inside a src prop instead of children but the error persists.如您所见,我尝试将代码传递到src prop 而不是children但错误仍然存​​在。

I "solved" it using redux and updating the action:我使用 redux 并更新操作“解决”了它:

export const changeWorkspace = (workspaceId: number) => async (dispatch: any) => {
  await dispatch({
    type: WORKSPACE_CHANGE,
    workspaceId,
  });

  return dispatch({
    type: WORKSPACE_SET,
    workspaceId,
  });

  localStorage.setItem("selected-workspace", workspaceId);
};

//reducer:
   case WORKSPACE_CHANGE:
      return {
        ...state,
        status: Status.change,
        currentWorkspace: state.workspaces.find((workspace) => workspace.id === action.workspaceId),
      };

    case WORKSPACE_SET:
      return {
        ...state,
        status: Status.success,
      };

And then updating the loading spinner condition like so:然后像这样更新加载微调器条件:

  if (!currentWorkspace || workspaceState.status === Status.change || !workspaceId) {
    return <LoadingSpinner />;
  }

Which forces to re-render the whole component each time I change the workspace.每次我更改工作区时都会强制重新渲染整个组件。 (Status becomes change so it returns the loading spinner for a split millisecond and then renders the component again with the correct values) (状态变为change因此它返回加载微调器一毫秒,然后使用正确的值再次呈现组件)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM