首页 文章

没有redux的React导航状态管理

提问于
浏览
2

我正在为我的React Native项目使用React Navigation库,并努力了解如何使用它来处理状态 . 在正常的React Native应用程序中,我可以在顶级组件中拥有状态,并通过props从子组件弹出事件,但是使用React Navigation,我似乎无法将任何道具传递给用作屏幕的组件 .

通过阅读related GitHub issue之后,似乎库开发人员非常痴迷于强迫每个人使用某种全局事件处理程序 - redux或mobx,我猜 .

The handler需要修改以下state . 当我开始尝试在应用程序内移动状态时,我陷入困境,因为我无法弄清楚如何:

  • 将处理程序传递给TaskForm组件 .

  • 如果作为App.js的一部分呈现,则将状态作为props传递给TaskList

请避免回复“只使用redux” . 我相信在这个例子中使用redux将是一个巨大的矫枉过正 .

3 回答

  • 0

    我使用react native并在我的应用程序中反应导航而没有redux,到目前为止它工作得很好 . 诀窍是将 screenProps 一直传递到线下 .

    例如,我有一个更多视图 . 我创建了一个基本的更多视图,在堆栈中有2个子视图:

    class More extends Component {
        render() {
            return <something>
        }
    }
    
    class SubView1 extends Component {...}
    class SubView2 extends Component {...}
    

    然后我创建堆栈:

    const MoreStack = StackNavigator({
    More: {
        screen: More
    }, 
    SubView1: {
        screen: SubView1,
    },
    ...
    }, options);
    

    然后我创建一个我导出的包装类:

    export default class MoreExport extends Component {
        static navigationOptions = {
            title: "More"
        }
    
        render() {
            return <MoreStack screenProps={this.props.screenProps} />;
        }
    }
    

    如果所有这些都在More.js中,我可以从More.js导入更多并在其他任何地方使用它 .

    如果我然后将screenProps传递给我的根视图,然后为每个图层都有一个包装类,我可以将screenProps一直传递下去,并且所有视图都可以使用 this.props.screenProps 访问它们 .

    我在每个StackNavigator和TabNavigator周围使用了一个类似于上面的包装器,并且screenProps一直向下传递 .

    例如,在我的根类的render方法中,我可以这样做:

    return <More screenProps={{prop1: something, prop2: somethingElse}} />
    

    然后MoreStack中的More类和每个SubView都可以访问这些道具 .

    如果您想要更多说明,请随时告诉我!

    免责声明:我不知道这是否是正确的或推荐的方式,但它确实有效

  • 3

    在受到steffeydev的启发之后,我更多地围绕反应社区问题,发现了一个使用函数的包装器的一个非常简单的例子 .

    令人惊讶的是simple solution并且我以前没想过 . 功能如下: const createComponent = (instance, props) => navProps => React.createElement(instance, Object.assign({}, props, navProps));

    感谢您的灵感,并指向screenProps,这使我找到了这个解决方案 .

  • 0

    您可以将param设置为导航,如下所示:

    static navigationOptions = ({ navigation }) => {
        return {
            tabBarIcon: ({ tintColor, focused }) =>
                <View>
                    <Icon name="bell-ring" size={24} color={focused ? 'green' : 'black'} />
                    {(navigation.state.params.badgeCount && navigation.state.params.badgeCount > 0) ?
                        <Text>{navigation.state.params.badgeCount}</Text>
                        :
                        <View></View>
                    }
                </View>
        }
    }
    

    并更改badgeCount:

    this.props.navigation.setParams({ badgeCount: 3 })
    

相关问题