我收到错误/警告“失败道具类型:道具one2many
在logged
中被标记为必需,但在App中的值为App
”。我无法弄清楚为什么它没有从商店获得价值。
index.js
undefined
loggedUserReducer.js
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import {BrowserRouter, Switch, Route, Redirect} from 'react-router-dom';
import {Provider, connect} from 'react-redux';
import store from './store/store';
import Signup from './components/Signup';
import Home from './components/Home';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
logged: this.props.logged
};
}
render() {
return (
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route exact path="/signup" component={Signup}/>
<Route exact path="/home" component={Home}/>
<Route exact path="/" render={() => (
this.state.logged ?
<Redirect to="/home" push/> : <Redirect to="/signup" push/>
)}/>
<Redirect to="/"/>
</Switch>
</BrowserRouter>
</Provider>
);
}
}
App.propTypes = {
logged: PropTypes.bool.isRequired
};
const stateToProps = (state) => ({
logged: state.loggedUserState.logged
});
connect(stateToProps)(App);
ReactDOM.render(<App/>, document.getElementById('root'));
store.js
const initialState = {
pending: true,
logged: false
};
const loggedUserReducer = (state = initialState, action) => {
if (action.type === 'GET_LOGGED_USER') {
return Object.assign({}, state, {
pending: false
});
}
return state;
};
export default loggedUserReducer;
答案 0 :(得分:2)
此代码
//- Everything else..
connect(stateToProps)(App); //- Assign App here!
ReactDOM.render(<App/>, document.getElementById('root'));
您忘记将应用分配给刚刚初始化的connect
ed应用。
这样做。
//- Everything else ...
App.propTypes = {
logged: PropTypes.bool.isRequired
};
const stateToProps = (state) => ({
logged: state.loggedUserState.logged
});
const ConnectedApp = connect(stateToProps)(App);
ReactDOM.render(<ConnectedApp/>, document.getElementById('root'));
<强>装修!强>
如果你有装饰者enabled,你也可以这样做。
@connect(state => ({
logged: state.loggedUserState.logged
})
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
logged: this.props.logged
};
}
render() {
return (
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route exact path="/signup" component={Signup}/>
<Route exact path="/home" component={Home}/>
<Route exact path="/" render={() => (
this.state.logged ?
<Redirect to="/home" push/> : <Redirect to="/signup" push/>
)}/>
<Redirect to="/"/>
</Switch>
</BrowserRouter>
</Provider>
);
}
}
App.propTypes = {
logged: PropTypes.bool.isRequired
};
ReactDOM.render(<App/>, document.getElementById('root'));
有关装饰者的更多信息,请参阅:this article
有关react / redux的更多信息,请参阅this
来自@markerikson的有关装饰者的警告,请参阅以下评论部分。
使用类似的装饰器和类型仍将导致a 警告。那是因为你将proptypes分配给包装器 connect生成的组件,而从mapState返回的数据 被赋予包装组件的道具。这是其中一个原因 为什么我们建议不要使用connect作为装饰器。