无法访问传递给子组件的道具

我正在使用 React 和 Redux,但是当我将数据从容器传递到子组件时。道具正在变成一个空的物体。这是我的容器组件。


class HeaderContainer extends React.Component {

    render() {

        return <Header searchByName = {this.props.searchByName} />

    }


}


const mapDispatchToProps = dispatch => {

    return bindActionCreators({

        searchByName: searchProviderByName.searchProviderByName

    }, dispatch)

}


export default connect(null, mapDispatchToProps)(HeaderContainer);

但是当我试图访问子组件中的数据时。它以空对象的形式出现。


export default function Header(props) {

 const performSearch = () => {

        props.searchByName(name,location); // getting undefined, props is empty object

 }

}


MM们
浏览 67回答 1
1回答

元芳怎么了

我已经从你的问题中获取了代码,并且可以证明它工作得很好(见下面的片段)。要么您搞砸了导入,要么searchProviderByName.searchProviderByName未定义,但 Header 仍然不会收到空道具。无法指出您的代码有什么问题,因为提供的代码可以正常工作,也许您可以提供一个片段或沙箱来演示您遇到的问题。const { Provider, connect } = ReactRedux;const {&nbsp; createStore,&nbsp; applyMiddleware,&nbsp; compose,&nbsp; bindActionCreators,} = Redux;const initialState = {};//action typesconst SOME_ACTION = 'SOME_ACTION';//action creatorsconst someAction = (...args) => ({&nbsp; type: SOME_ACTION,&nbsp; payload: args,});const reducer = (x) => x;//creating store with redux dev toolsconst composeEnhancers =&nbsp; window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;const store = createStore(&nbsp; reducer,&nbsp; initialState,&nbsp; composeEnhancers(&nbsp; &nbsp; applyMiddleware(() => (next) => (action) => {&nbsp; &nbsp; &nbsp; console.log('action:', action);&nbsp; &nbsp; &nbsp; return next(action);&nbsp; &nbsp; })&nbsp; ));function Header(props) {&nbsp; return (&nbsp; &nbsp; <button onClick={() => props.searchByName()}>&nbsp; &nbsp; &nbsp; click me&nbsp; &nbsp; </button>&nbsp; );}class HeaderContainer extends React.Component {&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <Header searchByName={this.props.searchByName} />&nbsp; &nbsp; );&nbsp; }}const mapDispatchToProps = (dispatch) => {&nbsp; return bindActionCreators(&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; searchByName: someAction,&nbsp; &nbsp; },&nbsp; &nbsp; dispatch&nbsp; );};const App = connect(&nbsp; null,&nbsp; mapDispatchToProps)(HeaderContainer);ReactDOM.render(&nbsp; <Provider store={store}>&nbsp; &nbsp; <App />&nbsp; </Provider>,&nbsp; document.getElementById('root'));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script><div id="root"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript