我如何访问并传递在return方法中定义的变量值,并将其传递给reactjs中的另一个组件?

时间:2018-10-05 12:47:44

标签: reactjs

我想传递在return方法中定义的变量值,并将其传递给另一个组件。

下面是代码段,

class componentname extends React.Component {
state = {
    cards: [],
};

render = () => {
    return (
        <div className="list">
                <table>
                    <thead>
                        <tr>
                            <th>name</th>
                            <th>something</th>
                            <th>noname</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.shares.map((share) => {
                            const card = this.props.cards.find(card => 
                                  card.id === share.card_id);
                                  return (
                                      <tr key={share.id}>
                                      <td>{card ? card.name : share.card_id 
                                      </td>
                                      <td>{card.recipient}</td>
                        </tbody></table>
                        );}
                        {this.state.open && <another_component cardname={want to pass card.name here}/>}

纸牌和股份是一系列对象,如下所示, 0:{名称:“名称”,说明:“”} 1:{name:“ name1”,说明:“}

我想要map方法中的card变量(在                             {this.state.shares.map((share)=> {                                 const card)进行全局访问,以便可以将其传递给another_component。有人可以帮我这个忙。谢谢。

2 个答案:

答案 0 :(得分:1)

您不能在render内执行此操作。您需要将其移到外部并执行以下操作:

componentDidMount() {
     this.state.shares.map((share) => {
         this.props.cards.find(card => 
              card.id === share.card_id);
              let returnedCard = cardVal ? card.name : share.card_id 
              this.setState({[card.id]:returnedCard})
     }
}

然后,您可以访问map中保存的所有值,并将其传递到所需的任何位置

答案 1 :(得分:0)

在componentDidMount中,您可以获取卡并将其添加到状态。

router.beforeEach((to, from, next) => {
  let nextParams
  let pageRequiresAuth    = to.matched.some(record => record.meta.requiresAuth)
  let userSignedIn        = store.getters['user/signedIn']

  if (pageRequiresAuth) {
    if (!userSignedIn) 
      nextParams = { path: paths.signInPath }  
  } else {
    if (userSignedIn)
      // don't let see auth pages after if user already signed in
      nextParams = { path: paths.afterSignInPath }
  }
  next(nextParams)
})