【问题标题】:How to use data from form to get data from api?如何使用表单中的数据从 api 获取数据?
【发布时间】:2018-12-11 16:54:46
【问题描述】:

我有一个响应表格,我要求提供汽车 VIN 的最后 8 个字符。获得该信息后,我想用它来获取汽车的所有位置。我该怎么做呢?我想调用操作,然后显示结果。

添加了减速器和动作...

这是我目前所拥有的......

class TaglocaByVIN extends Component {
constructor(props){
    super(props);
    this.state={
            searchvin: ''
    }
this.handleFormSubmit=this.handleFormSubmit.bind(this);
this.changeText=this.changeText.bind(this);

}
handleFormSubmit(e){
e.preventDefault();
let searchvin=this.state.searchvin;
//I want to maybe call the action and then display results
}

changeText(e){
this.setState({
    searchvin: e.target.value
})
}

render(){
return (
        <div>
    <form onSubmit={this.handleFormSubmit}>
    <label>Please provide the last 8 characters of VIN: </label>
    <input type="text" name="searchvin" value={this.state.searchvin} 
onChange={this.changeText}/>
    <button type="submit">Submit</button>

    </form>


        </div>
        );
}
  }
 export default TaglocaByVIN;

这是我的行动:

export function taglocationsHaveError(bool) {
return {
    type: 'TAGLOCATIONS_HAVE_ERROR',
    hasError: bool
};
 }

 export function taglocationsAreLoading(bool) {
  return {
    type: 'TAGLOCATIONS_ARE_LOADING',
    isLoading: bool
 };
 }

export function taglocationsFetchDataSuccess(items) {
return {
    type: 'TAGLOCATIONS_FETCH_DATA_SUCCESS',
    items
  };
}

export function tagformsubmit(data){
return(dispatch) =>{
    axios.get(`http://***`+data)
    .then((response) => {
        dispatch(taglocationsFetchDataSuccess);

    })
  };
}

减速器:

export function tagformsubmit(state=[], action){
switch (action.type){
case 'GET_TAG_FORM_TYPE':
    return action.taglocations;

    default:
        return state;
}

}

【问题讨论】:

  • 假设您设置了数据库...您是使用 graphql 来查询您的数据库还是 RESTful api?另外,查看您的 react-redux 标签,您是否为 get 信息设置了操作?
  • 是的,我有一个 rest api。我现在将添加我的操作.....

标签: reactjs react-redux redux-thunk


【解决方案1】:

这是一个简单的修复方法,但需要几个步骤:

  1. 设置动作

  2. 设置您的reducer

  3. 在组件中获取和渲染数据

创建动作

首先,您需要设置一个操作以获取基于VIN 的数据。看起来您的 tagformsubmit 函数具有此功能。我会在这里做一些调整。

您应该包含一个 catch 以便您知道是否出现问题,更改您的函数 param 以包含调度,向您的调度添加类型和有效负载,并修复您的 api 地址中的字符串文字。看起来很多,但它是一个快速修复。

从此更新您当前的代码:

export function tagformsubmit(data){
return(dispatch) =>{
    axios.get(`http://***`+data)
    .then((response) => {
        dispatch(taglocationsFetchDataSuccess);

    })
  };
} 

到这里:

//Get Tag Form Submit
export const getTagFormSubmit = vin => dispatch => {
  dispatch(loadingFunctionPossibly()); //optional
  axios
    .get(`/api/path/for/route/${vin}`) //notice the ${} here, that is how you use variable here
    .then(res =>
      dispatch({
        type: GET_TAG_FORM_TYPE,
        payload: res.data
      })
    )
    .catch(err =>
      dispatch({
        type: GET_TAG_FORM_TYPE,
        payload: null
      })
    );
};

创建减速器

不确定您是否已经创建了减速器。如果你有你可以忽略这个。创建你的 reducer 也很简单。首先你要定义你的初始状态然后导出你的函数。

例子

const initialState = {
  tags: [],
  tag: {},
  loading: false
};

export default (state=initialState, action) => {
    if(action.type === GET_TAG_FORM_TYPE){
        return {
          ...state, 
          tags: action.payload,
          loading: false //optional
        }
     }
     if(action.type === GET_TAG_TYPE){
        return {
          ...state, 
          tag: action.payload,
        }
     }
}

现在您已经有了 actionreducer,让我们来设置您的组件。

组件

我假设您知道所有必要的导入。在组件的底部,您要定义您的 proptypes。

TaglocaByVIN.propTypes = {
  getTagFormSubmit: PropTypes.func.isRequired,
  tag: PropTypes.object.isRequired
};

mapStateToProps

const mapStateToProps = state => ({
  tag: state.tag
});

connect 到组件:

export default connect(mapStateToProps, { getTagFormSubmit })(TaglocaByVIN);

更新您的提交以将数据传递给您的函数并获取返回的数据。

handleFormSubmit = (e) => {
e.preventDefault();
const { searchvin } = this.state;

this.props.getTagFormSubmit(searchvin); 

 const { tags } = this.props; 
 tags.map(tag => {
   //do something with that tag
}

将所有这些放在一起,您的组件应该如下所示(不包括导入):

class TaglocaByVIN extends Component {
  state = {
    searchvin: ""
  };

  handleFormSubmit = e => {
    e.preventDefault();
    const { searchvin } = this.state;

    this.props.getTagFormSubmit(searchvin);

    const { tags } = this.props.tag;
    if(tags === null){ 
       //do nothing
    } else{
       tags.map(tag => {
      //do something with that tag
     });
  };
}
  changeText = e => {
    this.setState({
      searchvin: e.target.value
    });
  };

  render() {
    return (
      <div>
        <form onSubmit={this.handleFormSubmit}>
          <label>Please provide the last 8 characters of VIN: </label>
          <input
            type="text"
            name="searchvin"
            value={this.state.searchvin}
            onChange={this.changeText}
          />
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

TaglocaByVIN.propTypes = {
  getTagFormSubmit: PropTypes.func.isRequired,
  tag: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  tag: state.tag
});

export default connect(
  mapStateToProps,
  { getTagFormSubmit }
)(TaglocaByVIN);

应该是这样的。希望这可以帮助。

【讨论】:

  • 非常感谢!我遇到了这个错误:Uncaught ReferenceError: getTags is not defined。什么是getTags??? @BensSteves
  • 好的,很好。我更新了那个。常量标签未随列表更新。我添加了“console.log(tags)”,它是一个空数组。如何将数据库中的内容放入数组或简单地显示在页面上?
  • 我仍然无法从“this.props.getTagFormSubmit(searchvin)”访问标签位置。我如何访问标签位置?需要帮助!!
  • 您的 getTagFormSubmit 返回什么值?在我提供的源代码中,我只输入了this.props.getTagFormSubmit(searchvin),但如果该方法具有返回的值,则必须将其设置为等于变量,例如 `const tagLocations = this.props.getTagFormSubmit(searchvin)。将该变量记录到控制台,看看是否有任何结果。
  • 未定义。我的减速机是否正确?现在添加到上面的代码.........
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 2015-06-01
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多