为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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 关注
  • 66 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信