![](/img/trans.png)
[英]Redux-React : How to pass the updated state to function onChange?
[英]Undefined redux-react state in componet
我正在实施一个项目,其中数据将在不同的组件中共享。 所以我决定使用 redux-react 进行状态管理。
我使用 redux react async api 调用从 api 获取数据。 但是,当组件第一次安装并返回实际数据时,我没有定义。
但是,当我尝试对返回的数据实现某些功能时,出现此错误:
“无法读取未定义的属性”
我可以在 redux 开发人员工具中看到状态,并且它有数据和日志功能正确显示操作。 我不明白为什么我变得不确定。 这是我的代码:
const initialState = {
candidate: {},
companies: [],
offers: [],
moreStatehere:...
}
候选人的减速器
export default function profileReducer(state = initialState, action) {
switch(action.type) {
case FETCH_POSTS_FAILURE:
return Object.assign({}, state, {
didInvalidate: true
})
case REQUEST_PROFILE:
return Object.assign({}, state, {
isFetching: true,
didInvalidate: false
})
case RECEIVE_PROFILE:
return {
...state,
candidate: action.data
}
default:
return state;
}
}
根减速机
const rootReducer = combineReducers({
profiles: profileReducer
})
export default rootReducer;
创建商店
const composeEnhanser = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__||compose;
const loggerMiddleware = createLogger()
export default function configureStore() {
return createStore(
rootReducer,
composeEnhanser(applyMiddleware(thunkMiddleware,
loggerMiddleware))
);
}
索引.js
const store = configureStore();
const app = (
<Provider store= {store}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>
)
ReactDOM.render(app, document.getElementById('root'));
registerServiceWorker();
动作创建者/api 调用
export function feachProfiles() {
return function (dispatch) {
dispatch(requestProfile)
return fetch(API_URL)
.then(
response => response.json(),
error => console.log('An error occurred.', error)
)
.then(json =>
dispatch(receiveProfile(json))
)
}
}
组件使用
class CandidatesList extends Component {
constructor (props){
super (props)
}
componentWillMount() {
this.props.feachProfiles();
}
handleClick() {
}
componentWillUnmount() {
}
render() {
const candidate = this.props.profiles.map(profile=>(
<div> </div>
));
return (
<div>
<ViewCandidate
/>
</div>
);
}
}
const mapStateToProps = state => {
return {
profiles: state.profiles.candidate || []
}
}
const mapDispatchToProps = (dispatch) => {
return {
feachProfiles: bindActionCreators(feachProfiles, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CandidatesList);
action RECEIVE_PROFILE @
redux-logger.js:1 prev state {profiles: {…}}
redux-logger.js:1 action {type: "RECEIVE_PROFILE", data: {…}}
redux-logger.js:1 next state {profiles: {…}}
确保在 map 函数之前写这个
if (this.props.profiles.length === 0) return null;
this.props.profiles 的数组长度应该大于 0
const candidate = this.props.profiles.map(profile=>(
<div> </div>
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.