简体   繁体   中英

How can I update the state by filtering the fetched data?

hi guys im trying to fetch data from my DB, which looks like this:

inputData: {
  formID: '',
  inputArr: [],
  labelArr: []
}

but I want to put only a specific formID string inside the state, basically filter them, how can I do that?

this is my fetch code

componentWillMount() {
  fetch('/api/datas')
    .then(data => data.json())
    .then(datas =>
      this.setState(state => ({ inputDataArr: [state.inputDataArr, ...datas] }))
    );
}

state = {
  inputDataArr: []

};

and I want to shove only those with the formID of 3 for example , would appreciate the help!

You can filter the datas before updating your state. Here is a working example.

 const datas = [ { formID: '3', inputArr: ["foo"], labelArr: ["foo"] }, { formID: '4', inputArr: ["bar"], labelArr: ["bar"] }, { formID: '3', inputArr: ["baz"], labelArr: ["baz"] }, ]; const fakeRequest = () => new Promise(resolve => setTimeout(() => resolve(datas), 1000)); class App extends React.Component { state = { inputDataArr: [], } componentDidMount() { fakeRequest() .then( datas => { const filterdDatas = datas.filter( data => data.formID === "3"); this.setState( currentState => ({ inputDataArr: [ ...currentState.inputDataArr, ...filterdDatas ] })) }) } render() { console.log( this.state ); return <div>Check the console.</div>; } } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

I'm mimicking the request here but you can apply the same logic in your last .then method. Also, use componentDidMount instead of componentWillMount since it will be deprecated.

The crucial part is this:

const filterdDatas = datas.filter( data => data.formID === "3");
    this.setState( currentState => ({
        inputDataArr: [ ...currentState.inputDataArr, ...filterdDatas ]
    }));

We are filtering the related data then updating the state using the current one. Just, do not forget to spread the current inputDataArr here or you get a nested array of an array and other data besides that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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