简体   繁体   English

在 React Native 中的两个不同屏幕之间传递数据的正确方法是什么?

[英]What is the correct way to pass data between two different screens in React Native?

The following examples are extremely simplified but still enough to sum up my question.以下示例非常简化,但仍然足以总结我的问题。 Currently I'm passing data (an object) between two screens using React Navigation parameters and it works just fine:目前我正在使用 React Navigation 参数在两个屏幕之间传递数据(一个对象),它工作得很好:

export const First screen = ({ navigation }) => {
  const object = {
    name:"John"
    surname:"Smith"
  };

  return (

      <Button
        onPress={() =>
          navigation.navigate("MainStack", {
                  screen: "SecondScreen",
                  params: { object: object },
                });
        }
      />
    </View>
  );
};
export const Second screen = ({ route }) => {
  const [object, setObject] = useState({});

  useEffect(() => {
    if (route.params?.object) setObject(route.params?.object);
  }, []);

  return (
    <View>
      <Text> {object.name} </Text>
      <Text> {object.surname} </Text>
    </View>
  );
};


However, as the docs say, this is considered to be an anti pattern, which makes sense because we are unnecessarily duplicating data:然而,正如文档所说,这被认为是一种反模式,这是有道理的,因为我们不必要地复制数据:

It's important to understand what kind of data should be in params.了解 params 中应该包含什么样的数据很重要。 Params are like options for a screen.参数就像屏幕的选项。 They should only contain information to configure what's displayed in the screen.它们应该只包含配置屏幕显示内容的信息。 Avoid passing the full data which will be displayed on the screen itself (eg pass a user id instead of user object).避免传递将显示在屏幕本身上的完整数据(例如传递用户 ID 而不是用户对象)。 Also avoid passing data which is used by multiple screens, such data should be in a global store.还要避免传递多个屏幕使用的数据,这些数据应该在全局存储中。

We obviously need to use some global state and then use navigation parameters to help us select the exact data that we need from it.我们显然需要使用一些全局 state 然后使用导航参数来帮助我们 select 我们需要的确切数据。 While Redux is probably an overkill, just using React Context is much more suitable for this situation.虽然 Redux 可能有点矫枉过正,但仅使用 React Context 更适合这种情况。 However, is there an even better way of doing it, a way that is considered to be best practice?但是,有没有更好的方法,一种被认为是最佳实践的方法?

To share data use the built in React Context and Provider.要共享数据,请使用内置的 React Context 和 Provider。 I'm pulling examples from a side project so forgive the names.我正在从一个侧面项目中提取示例,所以请原谅这些名称。

Start by building a Context.从构建上下文开始。 This example is for a Queue:此示例适用于队列:

// QueueContext.js
import { createContext, useContext } from "react";

const QueueContext = createContext({});

export function useQueueContext() {
    return useContext(QueueContext)
}

export default QueueContext;

You can pass data, functions, etc as your state.您可以将数据、函数等作为 state 传递。 Here I'm using a reducer as my state.在这里,我使用减速器作为我的 state。

// index.js
const [state, dispatch] = useReducer(QueueReducer, initialState);
const queueState = { state, dispatch };

<QueueContext.Provider value={queueState}>
    <App />
...

Now I can use this state in any component that is a child of the provider.现在我可以在作为提供者的子组件的任何组件中使用这个 state。

// my component
import { useQueueContext } from "../../contexts/QueueContext";
import Item from './Item';

export default function Queue() {
    const { state, _ } = useQueueContext()

    return (
        <>
            <div>Queue {state?.count}</div>
            <ul>
                {state?.items.map((item) => <Item key={item.id} props={item} />)}
            </ul>
        </>
    )
}

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

相关问题 React Native 在两个屏幕中的两个 class 组件之间传递数据 - React Native pass data between two class component in two screens react-native 如何在两个屏幕之间传递参数? - How to pass parameters between two screens in react native? 我如何在 React Native 的屏幕之间传递数据 - How I can pass data between screens in React Native 反应在两个屏幕之间进行本机导航 - React Native Navigating Between Two Screens 使用react native中的react-navigation在选项卡视图中的两个屏幕之间共享数据(数组) - Sharing data (an array) between two screens in tabs view using react-navigation in react native 如何在反应原生的屏幕之间传递变量(见附件) - How to pass variable between screens in react native (see attached) 传递数据以创建反应组件的正确方法是什么 - what is the correct way to pass data to create react componment 使用反应路由器获取数据并将其传递给路由的正确方法是什么? - What is the correct way to fetch data and pass it to a route with react router? React Native 中存储多屏幕中使用的全局应用程序数据的最佳方式是什么? - What is the best way in React Native to store global app data used in many screens? 如何在 react-native 中的两个功能组件之间传递数据? - How to pass data between two functional components in react-native?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM