在我的React组件中,我需要将Redux store中的状态作为属性获取并使用它们。我正在使用mapStateToProps,可以正确地从redux store中获取状态,因为初始值被正确地console.logged了。然而,当我使用它们时,我的组件中的所有属性都是未定义的。我没有进行任何明确的异步调用,这似乎是我找到的先前问题的问题,所以我不确定为什么我的组件无法访问这些属性。
src / components / SearchBar.js
src / components / SearchBar.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import actionType from '../constants/action-types';
class SearchBar extends Component {
render() {
return (
<form>
<input
type="text"
placeholder="Search..."
value={this.props.filterText}
onChange={this.onTextChange}
/>
<p>
<input
type="checkbox"
checked={this.props.inStockOnly}
onChange={this.onInStockCheckedChange}
/>
{' '}
Only show products in stock
</p>
</form>
);
}
}
function mapStateToProps(state) {
console.log("SearchBar state:", state);
return {
filterText: state.filterText,
showInStockOnly: state.showInStockOnly
};
}
function mapDispatchToProps(dispatch) {
return {
onTextChange: (evt) => {
const action = {
type: actionType.UPDATE_ON_TEXT_CHANGE,
value: evt.target.value
};
dispatch(action);
},
onInStockCheckedChange: () => {
const action = {
type: actionType.SET_IN_STOCK_ONLY_CHECKED,
};
dispatch(action);
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
src/reducers/searchBar_reducer.js
import actionType from '../constants/action-types';
import initialState from '../constants/initial-state';
const searchBar = (state = initialState, action) =>{
console.log('SearchBar reducer running: ', state, action);
switch (action.type) {
case actionType.UPDATE_ON_TEXT_CHANGE:
console.log("Text change action dispatched!")
return Object.assign({}, state, { filterText: action.value});
case actionType.SET_IN_STOCK_ONLY_CHECKED:
console.log("InStockOnly action dispatched!")
return Object.assign({}, state, { inStockOnly: !state.inStockOnly});
default:
return state;
}
}
export default searchBar;
src/reducers/index.js
import { combineReducers } from 'redux';
import searchBar from './searchBar_reducer'
const rootReducer = combineReducers({
searchBar
});
export default rootReducer;
src/index.js
import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
//import App from './components/App';
import SearchBar from './components/SearchBar'
import rootReducer from './reducers/';
const store = createStore(rootReducer);
const unsubscribe = store.subscribe(() =>
console.log(store.getState())
)
render(
<Provider store={store}>
<SearchBar />
</Provider>,
document.getElementById('root')
);