首页 > 解决方案 > 访问 URL 外的 axios body 参数

问题描述

我有这个 axios 请求:

 axios.all([

    axios.post(baseURL+'sentiments', {
      sentiment_type: 'positive',
      filter_tab: type
    }),

    axios.post(baseURL+'sentiments', {
      sentiment_type: 'negative',
      filter_tab: type
    })
])
    .then(axios.spread(result1, result2) => { 
          console.log(result1),
          console.log(result2)
    })
    .catch(err => {
          console.log(err)
    })

然后在我的渲染方法中,我想要实现的是将“sentiment_type”值“正”访问到某个变量或其他东西中,以进一步将其用于条件渲染。

if(sentiment_type === positive){ 
   then do this
 }
else{ 
      do something else
    }

有没有办法做到这一点?请指导。

标签: javascriptreactjsparametersaxios

解决方案


我假设这部分代码是组件的一部分。您可以将这些变量存储在本地存储中。以下是更多信息的链接:状态和生命周期

和一个例子,我希望这会对你有所帮助。

    class parentComponent extends React.Component {
  state = {
    sentiment_types: [];
  }

  componentDidMount() {
    axios.post(baseURL+'sentiments', {
              sentiment_type: 'positive',
              filter_tab: type
    })
    .then((firstResponse) => { 
            axios.post(baseURL+'sentiments', {
                sentiment_type: 'negative',
                  filter_tab: type
            })
            .then((secondResponse) => {
                // Here you can store you results into the state
                this.setState({
                    sentiment_types: ['positive', 'negative'];
                })
            })
            .catch(err => {
                console.log(err);
            })          
          console.log(result)
    })
    .catch(err => {
          console.log(err)
    })
  }

  render() {
   <childComponent sentiment_types={this.state.sentiment_types} />
  }
}

const childComponent = (props) => {
    if(props.state.sentiment_types.includes('positive')){
        return <h1>oke</h1>
    }
}

推荐阅读