我正在使用react-native,并且遇到一个问题,即我的动作正在分派,而reducer正在修改状态,但是我的组件没有重新渲染。我的减速器正在使用传播运算符来创建新对象。商店更新后,似乎没有再次调用mapStateToProps
。我不确定我缺少什么。
创建省份
class App extends React.Component {
render() {
return (
<Provider store={createStore(rootReducer, middleware)}>
<View style={styles.container}>
<DeckListScreen />
</View>
</Provider>
);
}
}
将组件连接到提供商
class DeckListScreen extends React.Component {
componentDidMount() {
this.props.dispatch(handleInitialData())
}
render() {
return(
<View>
<Text>{JSON.stringify(this.props.decks, null, 2)}</Text>
</View
)
}
}
function mapStateToProps({decks}) {
console.log('mapStateToProps - decks:', decks)
return {
decks: decks,
loading: Object.keys(decks).length === 0 ? true : false
}
}
export default connect(mapStateToProps)(DeckListScreen)
返回新对象的减速器
export default function decks(state = {}, action) {
switch(action.type) {
case GET_DECKS:
const { decks } = action
return {
...state,
...decks
}
default:
return state
}
}
这是控制台输出
Running application on iPhone.
mapStateToProps - decks: Object {}
mapStateToProps - decks: Object {}
ACTION TYPE:
GET_DECKS
OLD STATE:
Object {
"decks": Object {},
}
ACTION:
Object {
"decks": Object {
"JavaScript": Object {
"questions": Array [
Object {
"answer": "The combination of a function and the lexical environment within which that function was declared.",
"question": "What is a closure?",
},
],
"title": "JavaScript",
},
"React": Object {
"questions": Array [
Object {
"answer": "A library for managing user interfaces",
"question": "What is React?",
},
Object {
"answer": "The componentDidMount lifecycle event",
"question": "Where do you make Ajax requests in React?",
},
],
"title": "React",
},
},
"type": "GET_DECKS",
}
NEW STATE:
Object {
"decks": Object {
"JavaScript": Object {
"questions": Array [
Object {
"answer": "The combination of a function and the lexical environment within which that function was declared.",
"question": "What is a closure?",
},
],
"title": "JavaScript",
},
"React": Object {
"questions": Array [
Object {
"answer": "A library for managing user interfaces",
"question": "What is React?",
},
Object {
"answer": "The componentDidMount lifecycle event",
"question": "Where do you make Ajax requests in React?",
},
],
"title": "React",
},
},
}
答案 0 :(得分:1)
createStore(rootReducer, middleware)
需要被拉到App.js
以上的单独变量中。每次App
组件重新渲染时,都会创建一个新商店,该商店会还原您的reducer状态。