我正在尝试在安装屏幕时将用户元数据添加到我的商店中。但是,当我将动作发送给reducer时,商店没有被修改。
我希望发送动作后的道具如下:
{addUserMetaData: ƒ addUserMetaData(user_object),
user: {firestore_doc: {name: "Joe"}}
}
我在这里想念什么?
要复制,请react-native-init mwe
,然后添加以下代码。我在下面添加了应用日志的图片。
App.js
import React, { Component} from 'react';
import { View } from 'react-native';
import Screen from './src/screen';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const userReducer = function userReducer(state = {}, action) {
console.log('action', action);
switch (action.type) {
case "ADD_USER_METADATA":
return { ...state, firestore_doc: action.payload };
default:
return { ...state };
}
};
const store = createStore(userReducer);
export default class App extends Component {
render() {
return (
<Provider store={store}>
<View>
<Screen />
</View>
</Provider>
);
}
};
src / screen.js
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { connect } from 'react-redux';
const addUserMetaData = (user) => ({
type: "ADD_USER_METADATA",
payload: user
})
class Screen extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const user = { name: "Joe" };
console.log('props', this.props);
this.props.dispatch(addUserMetaData(user));
console.log('props after action', this.props);
}
render() {
return (
<View>
<Text>Welcome to react native</Text>
</View>
)
}
}
const mapStateToProps = state => {
return { user: state };
};
export default connect(mapStateToProps)(Screen);
答案 0 :(得分:0)
答案 1 :(得分:0)
请添加state.firestore_doc而不是state,因为在reducer动作中。payload将数据分配为firestore_doc状态,这样您就不会从state.user获取数据。
const mapStateToProps = state => {
return { user: state.firestore_doc };
};