页面刷新后useState值变得不确定

时间:2019-08-25 22:20:37

标签: reactjs redux react-redux react-hooks

现在我正在学习React + Redux 我正在做一个培训项目。

容器中有多个useState挂钩,这要归功于MapStateToProps从props获取初始状态。这些状态是几个插补的值。

如果我通过引用转到表格,它将成功地将数据提取到插补中, 但是,如果我刷新页面,则插补将变为空白,并且挂钩值未定义,尽管道具具有值

开发工具https://i.ibb.co/T0sGBdM/1.png

img

const PostEditorContainer = (props) => {

  const {fetchPosts,_id,text,title,imageUrl,history} = props;

  const [textNode,setText] = useState(text);
  const [titleNode,setTitle] = useState(title);
  const [imageUrlNode,setImageUrl] = useState(imageUrl);

  useEffect(() => {
    fetchPosts();
  },[]);

  const updatedData = {
    imageUrl: imageUrlNode,
    title: titleNode,
    text: textNode,
  };

  return (
    <>
      <HeaderBlock/>

      <AddForm
        title={titleNode}
        imageUrl={imageUrlNode}
        text={textNode}

        onChangeImage={e =>
          setImageUrl(e.target.value)
        }
        onChangeText={e =>
          setText(e.target.value)
        }
        onChangeTitle={e =>
          setTitle(e.target.value)
        }
        onSubmit={() => {
          PostApi.put(_id,updatedData)    
        }}
       />
    </>
  )
};


const mapStateToProps = ({posts},{match: {params:{id}}}) => {
  return posts.posts.filter(item => item._id === id)[0]
  console.log(posts);
};

export default withRouter(
  connect(mapStateToProps,PostListActions)(PostEditorContainer)
)


采取更多行动的行动

const PostListActions = {
  showPosts: (posts) => {
    return {
      type: "POSTS:SET_POSTS",
      payload: posts
    }
  },

  fetchPosts: () => dispatch => {
    PostApi.get().then(({data}) => {
      dispatch(PostListActions.showPosts(data))
    })
  },

};

export default PostListActions;

存储img https://i.ibb.co/R7pMqW0/2.png

0 个答案:

没有答案