This is the 28th day of my participation in the First Challenge 2022.

The React framework is results-oriented for those who have just learned the Front Three and want to learn the React framework quickly (history and unnecessary introductions are omitted).

  • Quick Start
  • The road to React

JSX inline handler function

So far, the stories list we have is just a stateless variable that filters the rendered list through search, but the list itself remains the same.

If we want to add a “delete items from list” function to take control of the list, we can use the list as the initial state of the useState hook (we don’t use our custom hook because we don’t want to display a cached list every time we open the browser). Then pass a callback handler down.

constinitialStories = [ ... ] ; .const App = () = >{...const [stories, setStories] = React.useState(initialStories);

  const handleRemoveStory = (item) = > {
    const newStories = stories.filter(
      (story) = >item.objectID ! == story.objectID ); setStories(newStories); }; .return (
    <>
      <InputWithLabel
        id="search"
        value={searchTerm}
        onInputChange={handleSearch}
        isFocused
      >
        <strong>Search:</strong>
      </InputWithLabel>

      <hr />
      <List list={searchedStories} onRemoveItem={handleRemoveStory} />
    </>
  );
};
Copy the code

The callback function receives the item to be deleted and sets the newStories returned to the new state.

The List component passes this function down to its children:

const List = ({ list, onRemoveItem }) = >
  list.map((item) = > (
    <Item key={item.objectID} item={item} onRemoveItem={onRemoveItem} />
  ));

const Item = ({ item, onRemoveItem }) = > (
  <div>
    <span>
      <a href={item.url}>{item.title}</a>
    </span>
    <span>{item.author}</span>
    <span>
      <button onClick={()= > onRemoveItem(item)}>Dismiss</button>
    </span>
  </div>
);
Copy the code

Using inline handlers, onRemoveItem() in the App component is called when the button is clicked to trigger the delete event.

It is similar to a regular handler, except that the body of the handler is in JSX, but because the JS logic is hidden in JSX, it can make the code difficult to debug, so we should avoid using inline handlers and go straight to the regular way, like this:

const Item = ({ item, onRemoveItem }) = > {
  const handleRemoveItem = () = > {
    onRemoveItem(item);
  };
 
  return (
    <div>
      <span>
        <a href={item.url}>{item.title}</a>
      </span>
      <span>{item.author}</span>
      <span>
        <button onClick={handleRemoveItem}>Dismiss</button>
      </span>
    </div>
  );
};
Copy the code

Asynchronous data

In a real application, we would normally render a component and then ask a third-party API to get the data and display it on the component.

We use an empty array as the initial state, and then use a simple promise function with a bit of delay to [simulate asynchronously retrieving data] :

const getAsyncStories = () = >
  new Promise((resolve) = >
    setTimeout(() = > resolve({ data: { stories: initialStories } }), 2000));const App = () = >{...const [stories, setStories] = React.useState([]);

  React.useEffect(() = > {
    getAsyncStories().then((res) = >{ setStories(res.data.stories); }); } []); . };Copy the code

Since useEffect’s dependent array is [empty array], the side effect function is executed only after the component is first rendered. After the function resolves the promise and changes the state, the component is rendered again and displays asynchronously loaded data.

Here’s an example of how promise can be used. See the documentation to read more.

const makeServerRequest = new Promise((resolve, reject) = > {
  // Do some asynchronous operations, assuming data is fetched from a remote API
  
  Call resolve(), reject()
  if(responseFromServer) {
    resolve("We got the data");
  } else {  
    reject("Data not received"); }});// resolve() is called at execution time
makeServerRequest.then(result= > {
  console.log(result); // "We got the data"
});

// reject() is called when executed
makeServerRequest.catch(error= > {
  console.log(error); // "Data not received"
});
Copy the code

column

Because clocking in is daily, it can be short, so check out the React Primer.

After the update, it will be integrated into a whole article, thanks for your attention and thumbs up!