[英]Redux React. Connect doesn't update state of component
I have a problem with using Redux. 我在使用Redux时遇到问题。 I have created Reducer and it works fine, But the component state does not update.
我已经创建了Reducer,并且工作正常,但是组件状态没有更新。 I saw some answers with similar problems but solutions don't work for me.
我看到了一些类似问题的答案,但是解决方案对我不起作用。
Reducer1: Reducer1:
export default (state = null, action) => {
switch (action.type) {
case 'select_library':
return action.payload
default:
return null;
}
}
Reducer2: Reducer2:
import data from './LibraryList.json';
export default () => data;
reducers: 减速器:
export default combineReducers({
libraries: LibraryReducer,
selectedlibraryId: SelectionReducer
});
Action: 行动:
export const selectLibrary = (libraryId) => {
return {
type: 'select_library',
payload: libraryId
};
}
App: 应用程序:
const store = createStore(reducers);
const App = () => {
return (
<Provider store={store}>
<View style={{ flex: 1}}>
<Header headerText="Tech Stack" />
<LibraryList />
</View>
</Provider>
)
}
export default App;
LibraryList (works fine): LibraryList(工作正常):
class LibraryList extends Component {
renderItem(library) {
return <ListItem library={library} />
}
render() {
return (
<FlatList
data={this.props.libraries}
renderItem={this.renderItem}
keyExtractor={(library) => library.id.toString()}
/>
)
}
}
const mapStateToProps = state => {
return { libraries: state.libraries }
}
export default connect(mapStateToProps)(LibraryList);
ListItem (problem here) is not call render after click ( click call mapStateToProps
): 单击(单击调用
mapStateToProps
)后,ListItem(这里的问题)未调用渲染:
class ListItem extends Component {
renderDescription() {
const {library, selectedLibraryId } = this.props
if (library.item.id === selectedLibraryId) {
return (
<Text>{library.item.description}</Text>
)
}
}
render() {
const { titleStyle } = styles
const { id, title } = this.props.library.item
return (
<TouchableWithoutFeedback
onPress={() => {
this.props.selectLibrary(id)
}
}
>
<View>
<CardSection>
<Text>
{title}
</Text>
</CardSection>
{this.renderDescription()}
</View>
</TouchableWithoutFeedback>
)
}
}
const mapStateToProps = state => {
return { selectedLibraryId: state.selectedLibraryId }
}
export default connect(mapStateToProps, actions)(ListItem);
i guess you are missing mapDispatchToProps function which will dispatch your action to reducer.? 我想你缺少mapDispatchToProps函数,它将把你的动作分派给reducer。 Something like this:
像这样:
const mapStateToProps = state => { return { selectedLibraryId: state.selectedLibraryId } } const mapDispatchToProps = (dispatch) => { return { onLibraryClick: (id) => { dispatch(actions.selectLibrary(id)) } } } export default connect(mapStateToProps, mapDispatchToProps)(ListItem);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.