【问题标题】:ReactJS save submission from input for other API callsReactJS 从输入中保存提交以供其他 API 调用
【发布时间】:2018-10-24 21:07:08
【问题描述】:

我正在开发一个 React Web 应用程序,需要保存表单提交中的输入,以便在多个 API 调用中重复使用。

我最初可以使用输入来进行 API 调用并显示结果,但我无法从表单中保存该输入以进行另一次调用。最终目的是让用户在输入搜索词后能够点击一个按钮以根据其他条件过滤响应。

我已经在下面注明了我想在代码中执行但不起作用的操作:

class Search extends Component {
  constructor(props) {
    super(props);

    this.state = {
        data: [],
        inputValue: '',
    };
  }

  onInitialSearch = (e) => {
    e.preventDefault();

    ////this value is what I use in the initial API call which is working
    const { value } = this.input;

    ////this is what I'd like to be able to do but isn't working
    //this logs nothing in console
    this.setState({ inputValue : this.input}), function () {
        console.log("inputValue  is ",this.state.inputValue);
    };

    if (value === '') {
        return;
    }
    this.fetchStories(value);
  }

  fetchStories = (value) => {
    axios.get(getNews(value))
        .then(response => {
            this.setState({data: response.data.articles});
        })
  }

   render() {
     return (
            <div className="page">
                <div className="App-search">
                    <form type="submit" onSubmit={this.onInitialSearch}>
                        <input type="text" ref={node => this.input = node} />
                        <button type="submit">Search</button>
                    </form>
                </div>
                <div>
                    <List list={this.state.data} />
                 </div>
            </div>
    );
}
}

export default Search

【问题讨论】:

  • 你为什么不把搜索状态放到另一个组件中,比如说SearchContainer,然后你可以将你的过滤器和搜索表单添加为子元素并传递状态?这样,即使您完全删除了搜索字段子项,您的状态仍然存在。

标签: node.js forms reactjs variable-assignment


【解决方案1】:

使输入字段受控。

<input type="text" onChange={(e) => this.setState({inputValue: e.target.value})} value={this.state.inputValue} />

并且onInitialSearch 函数可以使用来自 state 的值,而无需使用 refs。提交后该值不会被删除,因此您可以在需要时重复使用它。

有关受控和非受控组件的更多信息,请参阅:https://medium.com/@peter.yun.kim/controlled-and-uncontrolled-input-values-in-react-907119cc98d4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 2021-12-20
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    相关资源
    最近更新 更多