在我的react组件中,我需要从Redux存储中获取状态作为props并使用它们。我正在使用mapStateToProps,它正确地从redux存储获取状态,因为初始值正确地记录在console.log中。但是,当我使用它们时,组件中的所有道具都是不确定的。我没有进行任何显式的异步调用,这在我之前发现的问题中似乎是问题所在,因此我不确定为什么我的组件无法访问这些道具。
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')
);
答案 0 :(得分:2)
这是因为您正在尝试访问state.filterText
,而该减速器的数据存储在searchBar
中,因此您应该使用state.searchBar.filterText