简体   繁体   English

如何进行追加输入并将值发送到数组和 Axios.post

[英]how to make an appending input and send value to an array and Axios.post it

I want to know how to make a button that makes a new <input> everytime user clicks it and I want its value to be added to an array and post it with Axios.我想知道如何制作一个按钮,每次用户点击它时都会生成一个新的<input>并且我希望它的值被添加到一个数组中并用 Axios 发布它。

(I used this piece of code for the most of my pages and works fine, but if I need to change it for posting arrays please tell me) (我在大部分页面上都使用了这段代码并且工作正常,但是如果我需要更改它以发布数组,请告诉我)

    function roundTable() {
      const config = {
        headers: {
          "x-auth-token": sessionStorage.getItem('token'),
          "Accept": "application/json",
          "Content-Type": "application/json",
        }
      };
    
      const bodyParameters = { ... };
    
      const handleAdd = () => {
  const handleAdd = () => {
    setLoading(true);
    axios.post('localhost', bodyParameters, config).then(response => {
      setLoading(false);
      console.log(response)        })
      }

mostly I want to know how can I put a group of input values, to an array React is really new to me, id be very happy if someone could help me with this!主要是我想知道如何将一组输入值放入数组 React 对我来说真的很陌生,如果有人能帮助我,我会很高兴!

I want to know how to make a button that makes a new every time user clicks it and I want its value to be added to an array and post it with Axios.我想知道如何制作一个按钮,每次用户单击时都会生成一个新按钮,我希望将其值添加到数组中并使用 Axios 发布。

It feels there are two questions in one here;感觉这里有两个问题; first is how to deal with the state (amount of inputs) and second how to save the array.首先是如何处理状态(输入量),其次是如何保存数组。

I can't really help with the second one without examining how setLoading exactly works, but I have a suggestion for dealing with the state.如果不检查 setLoading 究竟是如何工作的,我就无法真正帮助解决第二个问题,但我有一个处理状态的建议。 Add each input value as a string into an array and do something like this:将每个输入值作为字符串添加到数组中并执行如下操作:

 document.onreadystatechange = () => { const { useState } = React; function Boxes() { const [inputs, setInputs] = useState([]); const addInput = () => { setInputs(inputs.concat("abc")); }; const changeInput = (index, value) => { const updated = [...inputs]; updated[index] = value; setInputs(updated); }; const handleAdd = () => { alert("Saving " + JSON.stringify(inputs)); }; return ( <div> <p>inputs</p> {inputs.map((input, index) => { return ( <div key={index}><input type="text" value={input} onChange={(e) => changeInput(index, e.target.value)} /></div> ); })} <button onClick={addInput}>Add new input</button> <hr /> <button onClick={handleAdd}>Add</button> </div> ); } ReactDOM.render(<Boxes />, document.querySelector("#root")); };
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM