简体   繁体   English

无法在 React 组件中呈现 json

[英]unable to render json in react component

I'm having a bit of an issue rendering a JSON object in a React component.我在 React 组件中呈现 JSON object 时遇到一些问题。 I want to get the meaning of a random word and then render it in page.我想获取一个随机单词的含义,然后将其呈现在页面中。

My App.js;我的 App.js;

function App() {
const [meaning,setMeaning] = useState([]);
};

useEffect(()=>{
    getMeaning()
}, [])

const getMeaning = async ()=>{
  const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
 const data = await response.json();
  setMeaning(data) 
}

<AppContext.Provider value={{word,setWord, meaning,setMeaning}}

my Meaning.js我的意思.js

function Meaning(){
    const{
        meaning,
        setMeaning,
    } = useContext(AppContext);

    if (!meaning.length) return <div>loading</div>

    return{meaning}
// tried return json.stringify{meaning} as well //


}

I do receive the object as I can console.log it.我确实收到了 object,因为我可以控制台记录它。 How can I render it on page?如何在页面上呈现它? Where am I going wrong?我哪里错了?

Thanks in advance,提前致谢,

You can't render objects in React.你不能在 React 中渲染对象。 You can convert the object to a string and render the string if you like您可以将 object 转换为字符串并根据需要呈现字符串

return (
  <div>{JSON.Stringify(meaning)}</div>
)

Fixed it by changing the code a bit;通过稍微更改代码来修复它; the problem was with the indexing问题出在索引上

function Meaning() {
    const [meaning,setMeaning] = useState([]);
    
    const {
        correctWord
    } = useContext(AppContext)

    useEffect(()=>{
        axios.get(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
        .then(res=>{
            console.log(res)
            setMeaning(res.data[0])
            
        })
        .catch(err => {
            console.log(err)
            
        })
        
    },[])
  return (
<div>
        <ul>
                {
                    
                    <div>
                    {meaning.word} {""}
                    <p>{meaning.phonetic}</p>
                    <p>{meaning.meanings[0]?.partOfSpeech}</p>
                    <p>{meaning.meanings[0]?.definitions[0]?.definition}</p>
                    
                    </div>
                    
                }
        </ul> 
    </div>

I set the function in the Meaning.js and then just called the component in the App.js.我在 Meaning.js 中设置了 function,然后在 App.js 中调用了组件。

Thanks for taking time to try and help.感谢您花时间尝试提供帮助。

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

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