使用redux / react更改输入时获取JSON数据的问题

时间:2016-11-26 13:38:08

标签: reactjs redux

我尝试从https://jsonplaceholder.typicode.com/获取数据用于练习目的。我想用类型输入来获取/发布/评论等。

例如:当我输入"帖子"在textarea中,我从https://jsonplaceholder.typicode.com/posts

获取数据

然后当我输入"评论"时,我从https://jsonplaceholder.typicode.com/comments获取数据

它适用于静态集合const ROOT_URL =' https://jsonplaceholder.typicode.com/posts';

当我按下按钮时,我会使用静态网址获取数据,但是如果值不断变化则不确定如何操作。

STUCK HERE

如何修改SearchBar组件,从输入中获取信息值,然后在表单提交中,它将根据值获取数据?

我希望你理解我的问题,谢谢!

actions.js

export const fetchInfo = () => {
const url = `${ROOT_URL}$posts`;
const request = axios.get(url);
return {
  type: FETCH_INFO,
  payload: request
};
}
export function fetchInfoSuccess(posts) {
  return {
    type: FETCH_INFO_SUCCESS,
    payload: posts
  };
}

export function fetchInfoFailure(error) {
  return {
    type: FETCH_INFO_FAILURE,
    payload: error
  };
}

已修改的action.js(我想工作) 带参数(info)

export const fetchInfo = (info) => {
    const url = `${ROOT_URL}${info}`;
    const request = axios.get(url);
    return {
      type: FETCH_INFO,
      payload: request
    };
    }
    export function fetchInfoSuccess(posts) {
      return {
        type: FETCH_INFO_SUCCESS,
        payload: posts
      };
    }

    export function fetchInfoFailure(error) {
      return {
        type: FETCH_INFO_FAILURE,
        payload: error
      };
    }

SearchBarContainer.js

const mapDispatchToProps = (dispatch) => {
  return {
    fetch: () => {
      dispatch(fetchInfo()).then((response) => {
            !response.error ? dispatch(fetchInfoSuccess(response.payload)) : dispatch(fetchInfoFailure(response.payload));
          });
    }
  }
}

SearchBarComponent.js

 export default class SearchBar extends Component {
      constructor(props) {
      super(props)

      this.state = {info: ''};
    }

    onInputChange = (e) => {
      this.setState({info: e.target.value});
    }

       handleOnSubmit = (e) => {
       e.preventDefault();
      this.props.fetch();
    }

    render () {
      return (
    <div>
    <form onSubmit={this.handleOnSubmit}>
    <input onChange={this.onInputChange}/>

          <button type="submit">Search</button>
      </form>
        </div>
          )
    }
    }

STUCK HERE

如何修改SearchBar组件,从输入中获取信息值,然后在表单提交中,它将根据值获取数据?

1 个答案:

答案 0 :(得分:0)

如评论中所述,将输入组件更改为

<input onChange={this.onInputChange} />

使用两个事件操作(handleOnSubmit,onInputChange)绑定当前实例this。 在handleOnSubmit方法中,传递信息状态值

handleOnSubmit (e) {
   e.preventDefault();
  this.props.fetchInfo(this.state.info);
}

这可能会对您有所帮助https://facebook.github.io/react/docs/forms.html