gpt4 book ai didi

javascript - React Native+Redux : connect trouble

转载 作者:行者123 更新时间:2023-12-03 04:06:49 24 4
gpt4 key购买 nike

我对 React Native/Redux 还很陌生。为了研究我写了最简单的例子。但似乎连接不起作用。谁能解释一下为什么?

我的代码

import React, { Component } from 'react';
import {
AppRegistry,
Text,
View
} from 'react-native';
import { createStore } from 'redux';
import { connect, Provider } from 'react-redux';

function reducer(state, action) {
if( state === undefined )
return {
age: 31
};

return state;
}

var store = createStore(reducer);

const App = (props) => {
return (
<View>
<Text>Store: { JSON.stringify(store.getState()) }</Text>
<Text>Props: { JSON.stringify(props) }</Text>
</View>
);
}

class test0003 extends Component {
render() {
return (
<Provider store={store}>
<App/>
</Provider>
);
}
}

function mapStateToProps(state) {
return {
age: state.age
}
}
export default connect(
mapStateToProps
)(App);

AppRegistry.registerComponent('test0003', () => test0003);

输出

Store: {"age":31}
Props: {}

连接不起作用。这段代码有什么问题?

最佳答案

由于 Redux 需要分离表示组件和容器组件而出现问题。正确代码:

import React, { Component } from 'react';
import {
AppRegistry,
Text,
View
} from 'react-native';
import { createStore } from 'redux';
import { connect, Provider } from 'react-redux';

function reducer(state, action) {
if( state === undefined )
return {
age: 31
};

return state;
}

var store = createStore(reducer);

const App = (props) => {
return (
<View>
<Text>Store: { JSON.stringify(store.getState()) }</Text>
<Text>Props: { JSON.stringify(props) }</Text>
</View>
);
}

class test0003 extends Component {
render() {
return (
<Provider store={store}>
<AppContainer/>
</Provider>
);
}
}

function mapStateToProps(state) {
return {
age: state.age
}
}
var AppContainer = connect(
mapStateToProps
)(App);

AppRegistry.registerComponent('test0003', () => test0003);

connect 基于演示 App 创建容器 AppContainer

关于javascript - React Native+Redux : connect trouble,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com