简体   繁体   中英

Trying to return multiple values from react functional component method

I am trying to return a multiple values from the below method and getting an error like property assignment expected at the return statement and my method looks like this below,

export const useSectionQuery = (query, resultFieldName, updateState, transform, initialRevisionId) => {

  const [completed, setCompleted] = useState(false);
  let  transformed;
  const { loading, error } = useQuery(query, {
    variables: {
      where: initialRevisionId ? { initialRevisionId } : { isApproved: true },
      order_by: null
    },
    fetchPolicy: 'network-only',
    onCompleted: data => {
     transformed = transform ? transform(data[resultFieldName]) : data[resultFieldName];
      updateState(draft => {
        draft[resultFieldName] = transformed;
      });
      setCompleted(true);
    }
  });
  if (error) return errorRedirectElement(error, resultFieldName);
  return {(!completed || loading) && loadingElement, transformed };
};

and getting an error property assignment is expected at here in below line

 return {(!completed || loading) && loadingElement, transformed }

React v16.2 introduced another way of returning multiple elements. React.Fragment abstracted in JSX way via just an empty tag. Bare in mind that JSX syntax doesn't support attributes — use a verbose way if you need so. No extra components needed, no array notation, no keys. Nice!

You just need to wrap you code around with <React.Fragment> tag in the return statement

const App = () => (
  <React.Fragment>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
    <p>React 16 can return multiple elements ❤️</p>
  </React.Fragment>
);

your're not rendering with JSX you need to assign (!completed || loading) && loadingElement to a property name

so it should be

return {
  element: (!completed || loading) ? loadingElement : null, 
  transformed
}

if you're doing it within render() you could do this and it would work. Not when returning an object.

render() {
  {(!completed || loading) && loadingElement} 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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