【问题标题】:Populate a picker from code - React native从代码填充选择器 - React native
【发布时间】:2023-01-30 22:02:46
【问题描述】:

使用组件https://github.com/react-native-picker/picker,我试图创建一个使用来自 API 的值的下拉列表。 我在https://alexb72.medium.com/how-to-populate-react-native-picker-dynamically-with-values-from-an-api-dbe122e85a5a 上找到了这篇文章,其目的也是如此。 然而,它一开始就抛出错误,只是通过创建 App.js:

ERROR  ReferenceError: Can't find variable: React

ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). 
A frequent cause of the error is that the application entry file path is incorrect.
    This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). 
A frequent cause of the error is that the application entry file path is incorrect.
    This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

我在 Android 模拟器中运行。 有人有工作项目吗?

【问题讨论】:

  • 将新包添加到节点模块文件夹时有时会发生这种情况。尝试清理项目并再次运行它。如果这不起作用,请尝试像这样导入 React: import * as React from 'react';
  • 另外,分享一些导入代码和选择器的逻辑。

标签: react-native


【解决方案1】:

它不起作用的原因是文章使用了旧版本的 React Native。 取而代之的是:“class App extends React.Component {”,我们现在使用“const App = () => {”。 由于过时的命名法,代码的其他部分也会抛出错误。

我得到了工作列表,但是,它只能通过按下按钮来加载。在老版本的react native中有一个叫componentDidMount的函数,现在不能用了,在constructor中设置state会死循环渲染页面。你知道新的生命周期方法是什么吗?我还没有找到他们的任何文件。

这是我的代码:

import * as React from 'react';
import { useState } from 'react';
import { Button, SafeAreaView } from 'react-native';
import { Picker } from '@react-native-picker/picker';

const App = () => {
    const [users, setUsers] = useState();

    async function req() {
        let userValues = await fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json());

        setUsers(userValues.map((myValue,myIndex) => {
            console.log('User: ' + myValue.name + "  - " + myIndex);

            return(
                <Picker.Item label={myValue.name + ' - ' + myValue.username} value={myIndex} key={myIndex}/>
            )
        }))
    }

    return (
        <SafeAreaView>
            <Button
                color='green'
                title="Load users"
                onPress={() =>
                    req()
                }
            />
            <Picker
                mode="dialog"
                onValueChange={(itemValue, itemIndex) =>
                { 
                }}>
                {users}
            </Picker>
        </SafeAreaView>
    );
}

export default App;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 2020-07-15
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多