亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法訪問傳遞給子組件的道具

無法訪問傳遞給子組件的道具

MM們 2022-10-13 09:39:02
我正在使用 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 }}
查看完整描述

1 回答

?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

我已經從你的問題中獲取了代碼,并且可以證明它工作得很好(見下面的片段)。要么您搞砸了導入,要么searchProviderByName.searchProviderByName未定義,但 Header 仍然不會收到空道具。


無法指出您的代碼有什么問題,因為提供的代碼可以正常工作,也許您可以提供一個片段或沙箱來演示您遇到的問題。


const { Provider, connect } = ReactRedux;

const {

  createStore,

  applyMiddleware,

  compose,

  bindActionCreators,

} = Redux;


const initialState = {};

//action types

const SOME_ACTION = 'SOME_ACTION';

//action creators

const someAction = (...args) => ({

  type: SOME_ACTION,

  payload: args,

});

const reducer = (x) => x;

//creating store with redux dev tools

const composeEnhancers =

  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(

  reducer,

  initialState,

  composeEnhancers(

    applyMiddleware(() => (next) => (action) => {

      console.log('action:', action);

      return next(action);

    })

  )

);


function Header(props) {

  return (

    <button onClick={() => props.searchByName()}>

      click me

    </button>

  );

}

class HeaderContainer extends React.Component {

  render() {

    return (

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

    );

  }

}


const mapDispatchToProps = (dispatch) => {

  return bindActionCreators(

    {

      searchByName: someAction,

    },

    dispatch

  );

};


const App = connect(

  null,

  mapDispatchToProps

)(HeaderContainer);


ReactDOM.render(

  <Provider store={store}>

    <App />

  </Provider>,

  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>


查看完整回答
反對 回復 2022-10-13
  • 1 回答
  • 0 關注
  • 85 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號