最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Selecting item in array by index, while using React hooks - Stack Overflow

programmeradmin2浏览0评论

TL/DR: Having trouble referencing items in array by index (using React), could use some guidance.

I am attempting to create a ponent on my SPA out of data ing from an API. Using React hook useState and useEffect I have created state, done an axios call, and then set the response.data.articles to state (.articles is the array of objects I am using to create the dynamic content).

 function App() {

  const [storyArray, setStoryArray] = useState();

  useEffect(() => {
    axios.get('&apiKey=[redacted_key_value]')
      .then((response) => { 
        // console.log(response);
        setStoryArray(response.data.articles);
      })
      .catch((err) => {
        console.log(err);
      })
  }, [])

  console.log(storyArray)

  return (
    <div className="App">
      <Directory />
      <HeaderStory />
    </div>
  );
}

From here, my state is an array of objects. My goal is to pass THE FIRST object as props to the ponent <HeaderStory /> but any time I attempt to reference this array item with dot notation I am met with an undefined error. My attempt at circumventing this is problem was to set the item to a variable and then pass the variable as props to the ponent.

const firstStory = storyArray[0];

This also resulted in an undefined error. Looking for advice / assistance on referencing items in an array to be passed and used in React.

TL/DR: Having trouble referencing items in array by index (using React), could use some guidance.

I am attempting to create a ponent on my SPA out of data ing from an API. Using React hook useState and useEffect I have created state, done an axios call, and then set the response.data.articles to state (.articles is the array of objects I am using to create the dynamic content).

 function App() {

  const [storyArray, setStoryArray] = useState();

  useEffect(() => {
    axios.get('http://newsapi/v2/everything?domains=wsj.&apiKey=[redacted_key_value]')
      .then((response) => { 
        // console.log(response);
        setStoryArray(response.data.articles);
      })
      .catch((err) => {
        console.log(err);
      })
  }, [])

  console.log(storyArray)

  return (
    <div className="App">
      <Directory />
      <HeaderStory />
    </div>
  );
}

From here, my state is an array of objects. My goal is to pass THE FIRST object as props to the ponent <HeaderStory /> but any time I attempt to reference this array item with dot notation I am met with an undefined error. My attempt at circumventing this is problem was to set the item to a variable and then pass the variable as props to the ponent.

const firstStory = storyArray[0];

This also resulted in an undefined error. Looking for advice / assistance on referencing items in an array to be passed and used in React.

Share Improve this question asked Mar 16, 2020 at 1:38 AvantGovAvantGov 151 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

On the first render the storyArray will have no value/undefined, The useEffect hook will execute only after ponent mount.

So you have to render the ponent conditionally, if the storyArray has value then only render the HeaderStory.

Example:

function App() {
    const [storyArray, setStoryArray] = useState();
    useEffect(() => {
        axios.get('http://newsapi/v2/everything?domains=wsj.&apiKey=[redacted_key_value]')
            .then((response) => {
                // console.log(response);
                setStoryArray(response.data.articles);
            })
            .catch((err) => {
                console.log(err);
            })
    }, [])

    return (
        <div className="App" >
            <Directory />
            {storyArray && <HeaderStory firstStory={storyArray[0]} />}
        </div>
    );

}

You should init default value for storyArray.

Example code:

function App() {

  const [storyArray, setStoryArray] = useState([]); //Init storyArray value

  useEffect(() => {
    axios.get('http://newsapi/v2/everything?domains=wsj.&apiKey=[redacted_key_value]')
      .then((response) => { 
        // console.log(response);
        setStoryArray(response.data.articles);
      })
      .catch((err) => {
        console.log(err);
      })
  }, [])

  console.log(storyArray)

  return (
    <div className="App">
      <Directory />
      <HeaderStory firstStory={storyArray[0] || {}} />
    </div>
  );
}

I set props firstStory={storyArray[0] || {}} because if storyArray[0] is undefined then pass empty object "{}" for firstStory prop.

发布评论

评论列表(0)

  1. 暂无评论