我在使用Redux时遇到问题。我已经创建了Reducer,并且工作正常,但是组件状态没有更新。 我看到了一些类似问题的答案,但解决方案对我不起作用。
Reducer1:
export default (state = null, action) => {
switch (action.type) {
case 'select_library':
return action.payload
default:
return null;
}
}
Reducer2:
import data from './LibraryList.json';
export default () => data;
减速器:
export default combineReducers({
libraries: LibraryReducer,
selectedlibraryId: SelectionReducer
});
操作:
export const selectLibrary = (libraryId) => {
return {
type: 'select_library',
payload: libraryId
};
}
应用程序:
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(工作正常):
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(这里的问题)在单击(单击调用mapStateToProps
)后未调用渲染:
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);
答案 0 :(得分:0)
我想您缺少mapDispatchToProps函数,该函数会将您的操作分派给reducer。像这样:
const mapStateToProps = state => {
return { selectedLibraryId: state.selectedLibraryId }
}
const mapDispatchToProps = (dispatch) => {
return {
onLibraryClick: (id) => {
dispatch(actions.selectLibrary(id))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ListItem);