logo资料库

Learn React with TypeScript 3.2018.pdf

第1页 / 共492页
第2页 / 共492页
第3页 / 共492页
第4页 / 共492页
第5页 / 共492页
第6页 / 共492页
第7页 / 共492页
第8页 / 共492页
资料共492页,剩余部分请下载后查看
Cover
Title Page
Copyright and Credits
About Packt
Contributors
Table of Contents
Preface
Chapter 1: TypeScript Basics
Technical requirements
Understanding the benefits of TypeScript
Catching coding errors early
Better developer experience and productivity
Using future JavaScript features
Understanding basic types
Primitive types
Type annotations
Type inference
Any
Void
Never
Enumerations
Objects
Arrays
Creating interfaces, types aliases, and classes
Interfaces
Properties
Method signatures
Optional properties and parameters
Readonly properties
Extending interfaces
Type aliases
Classes
Basic classes
Implementing interfaces
Constructors
Extending classes
Abstract classes
Access modifiers
Property setters and getters
Static
Structuring code into modules
Module formats
Exporting
Importing
Default exports
Configuring compilation
Common options
--target
--outDir
--module
--allowJS
--watch
--noImplicitAny
--noImplicitReturns
--sourceMap
--moduleResolution
tsconfig.json
Specifying files for compilation
TypeScript linting
Installing TSLint
Configuring rules
Built-in rules
Excluding files
Code formatting
Summary
Questions
Further reading
Chapter 2: What is New in TypeScript 3
Technical requirements
Tuples
JavaScript rest and spread syntax
Open-ended tuples
Tuple function parameters
Spread expressions
Empty tuples
Optional tuple elements
The unknown type
Type checking with a type predicate
Type narrowing with a type assertion
Project references
Setting up an example
Referencing projects 
Additions to compiler options
Cross-project Go to Definition
Build mode
Default JSX properties
Summary
Questions
Further reading
Chapter 3: Getting Started with React and TypeScript
Technical requirements
Creating a React and TypeScript project
Using create-react-app
Creating a project manually
Creating our folder structure
Creating package.json
Adding TypeScript
Creating tsconfig.json
Adding TSLint
Adding React with types
Creating a root web page
Creating a simple React component
Adding webpack
Project folders and files
Creating start and build scripts
Creating a class component
Creating a basic class component
JSX
Component props
Optional props
Default prop values
Handling class component events
Basic event handlers
The this problem
Function props
Class component states
Defining state type
Initializing the state
Changing state
Class component life cycle methods
componentDidMount 
componentWillUnmount
getDerivedStateFromProps
getSnapshotBeforeUpdate and componentDidUpdate
shouldComponentUpdate
Deprecated life cycle methods
Creating a function component
Creating a basic function component
Stateful function components
Function component life cycle hooks
Optimizing function component rendering
Summary
Questions
Further reading
Chapter 4: Routing with React Router
Technical requirements
Installing React Router with routing types
Declaring routes
Creating navigation
Using the Link component
Using the NavLink component
Route parameters
Handling not found routes
Implementing page redirects
Simple redirect
Conditional redirect
Query parameters
Route prompts
Nested routes
Animated transitions
Lazy loading routes
Summary
Questions
Further reading
Chapter 5: Advanced Types
Technical requirements
Union types
String literal types
String literal union types
Discriminated union pattern
Type guards
Using the typeof keyword 
Using the instanceof keyword 
Using the in keyword 
Using a user-defined type guard
Generics
Generic functions
Generic classes
Overload signatures
Lookup and mapped types
Summary
Questions
Further reading
Chapter 6: Component Patterns
Technical requirements
Container and presentational components
Compound components
Adding reviews to a product
Creating a basic tab component
Leveraging the compound component pattern
Sharing state with React context
Render props pattern
Completing Tabs with render props
Using render prop for tab headings
Using children prop for tab content 
Higher-order components
Adding asynchronous data fetching
Implementing the withLoader HOC
Consuming the withLoader HOC
Summary
Questions
Further reading
Chapter 7: Working with Forms
Technical requirements
Creating a form with controlled components
Adding a Contact Us page
Creating controlled inputs
Reducing boilerplate code with generic components
Creating a basic form component
Adding a basic Field component
Sharing state with React context
Implementing our new ContactUs component
Validating forms
Adding a validation rules prop to form
Tracking validation error messages
Invoking validation rules
Triggering validation rule execution from field
Rendering validation error messages
Form submission
Adding a submit button to the form
Adding a onSubmit form prop
Consuming the onSubmit form prop
Summary
Questions
Further reading
Chapter 8: React Redux
Technical requirements
Principles and key concepts
Principles
Key concepts
Installing Redux
Creating actions
Creating state and action types
Creating actions
Creating reducers
Creating a store
Connecting our React app to the store
Adding the store Provider component
Connecting components to the store
Connecting ProductsPage to the store
Connecting ProductsPage to the loading store state
Adding product state and actions to the store
Adding basket state and actions to the store
Connecting ProductPage to the store
Creating and connecting BasketSummary to the store
Managing state with useReducer
Summary
Questions
Further reading
Chapter 9: Interacting with RESTful APIs
Technical requirements
Writing asynchronous code
Callbacks
Callback execution
Handling callback errors
Promises
Consuming a promised-based function
Creating a promised based function
async and await
Using fetch
Getting data with fetch
Basic GET request
Getting response status
Handling errors
Creating data with fetch
Basic POST request
Request HTTP headers
Changing data with fetch
Basic PUT request
Basic PATCH request
Deleting data with fetch
Using axios with class components
Installing axios
Getting data with axios
Basic GET request
Handling errors
Request HTTP headers
Timeouts
Canceling requests
Creating data with axios
Updating data with axios
Deleting data with axios
Using axios with function components
Summary
Questions
Further reading
Chapter 10: Interacting with GraphQL APIs
Technical requirements
GraphQL query and mutation syntax
Reading GraphQL data
Basic query
Returning nested data
Query parameters
Writing GraphQL data
Using axios as a GraphQL client
Getting a GitHub personal access token
Creating our app
Querying the GraphQL server
Using Apollo GraphQL client
Installing Apollo client
Migrating from axios to Apollo
Adding an Apollo provider
Using the query component to query GraphQL
Adding a repository search component
Implementing the search form
Implementing the search query
Rendering the search result
Implementing a mutation with Apollo
Working with cached data in Apollo
Clearing the caching using refetchQueries
Updating the cache after a Mutation
Summary
Questions
Further reading
Chapter 11: Unit Testing with Jest
Technical requirements
Testing pure functions
Creating a basic pure function test
Understanding Jest watch options
Adding structure to unit test results
Testing components
Creating a basic component test
Improving our tests with react-testing-library
Installing react-testing-library 
Removing CSS class references from our tests
Using fireEvent for user interaction
Creating a second test for a valid form submission
Using Jest snapshot tests
Mocking dependencies
Using a mock function in Jest
Mocking Axios with axios-mock-adapter
Getting code coverage
Summary
Questions
Further reading
Answers
Chapter 1: TypeScript Basics
Chapter 2: What is New in TypeScript 3
Chapter 3:  Getting Started with React and TypeScript
Chapter 4: Routing with React Router
Chapter 5: Advanced Types
Chapter 6: Component Patterns
Chapter 7:  Working with Forms
Chapter 8: React Redux
Chapter 9: Interacting with RESTful APIs
Chapter 10: Interacting with GraphQL APIs
Chapter 11: Unit Testing with Jest
Other Books You May Enjoy
Index
Learn React with TypeScript 3 Beginner's guide to modern React web development with TypeScript 3 Carl Rippon BIRMINGHAM - MUMBAI
Learn React with TypeScript 3 Copyright © 2018 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Commissioning Editor: Amarabha Banerjee Acquisition Editor: Devanshi Doshi Content Development Editor: Francis Carneiro Technical Editor: Surabhi Kulkarni Copy Editor: Safis Editing Project Coordinator: Kinjal Bari Proofreader: Safis Editing Indexer: Rekha Nair Graphics: Alishon Mendonsa Production Coordinator: Aparna Bhagat First published: November 2018 Production reference: 1281118 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78961-025-3 www.packtpub.com
mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content Packt.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details. At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Contributors About the author Carl Rippon has been involved in the software industry for over 20 years, developing a complex line of business applications in various sectors. He has spent the last eight years building single page applications using a wide range of JavaScript technologies, including Angular, ReactJS, and TypeScript. Carl has written over 100 blog posts on various technologies. I'd like to thank Sarah, Ellie-Jayne, and Lily-Rose for all the support they've given me while writing this book. Thanks to everyone in the Packt editorial team for their hard work and great feedback, especially Francis Carneiro and Surabhi Kulkarni. Special thanks also to Devanshi Doshi for reaching out to me with this opportunity.
About the reviewers Ashok Kumar S has been working in the mobile development domain for about six years. In his early days, he was a JavaScript and Node developer. Thanks to his strong web development skills, he has mastered web and mobile development. He is a Google-certified engineer, a speaker at global level conferences (including DroidCon Berlin and MODS), and he also runs a YouTube channel called AndroidABCD for Android developers. He is a computer science and engineering graduate who is passionate about innovation in technology. He contributes to open source heavily with a view to improving his e-karma. He has also written books on Wear OS programming and mastering the Firebase toolchain. In his spare time, he writes articles and makes videos on programming. Ashok Kumar has also reviewed books on mobile and web development, namely Mastering JUnit 5, Android Programming for Beginners, and developing Enterprise applications using JavaScript. I would especially like to thank my mother for her boundless support in every possible way, not to mention family members Shylaja, Sumitra, Krishna, Vinisha, and my fiancé, Geetha Shree. Dave has had over 16 years' experience as a software engineer. After working for a number of creative agencies in London and then as a contract tech lead for a global e-commerce company, he is now tech lead at Seccl Technology, a start-up based in Bath, UK, that is building pioneering digital services for the financial industry, working with a serverless infrastructure in the cloud, and providing wonderful experiences through their web applications. He has worked with TypeScript for about five years and has seen it mature a lot over the years. Dave has worked specifically on React applications for over two years, as well on serverless code for the Seccl platform. Pogo Kid is Dave's consultancy where he provides support for companies wanting to improve their serverless, React, and TypeScript applications. He has also reviewed a couple of book proposals for Manning on TypeScript. He has had the privilege of bringing leadership to development teams across the world, including many household names. He is a firm believer that when systems have the correct architecture and the team has a good mix of passion and skill, users will have a wonderful experience.
Daniel Deutsch is working as a web developer in various companies. Although most of his work is structured around client-side development, he is also able to contribute to different problem areas in software development, like the backend, devops, or project management. Coming from legal fields and also studying law he aims for bringing the 2 areas together and create additional value for both industries. As his personal interest focuses on machine learning, he likes to incorporate more of those disciplines in his day to day work. Daniel's ultimate goal is to structure a business around motivated people to create something that brings value to humanity and lasts for a long time period. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Table of Contents Preface Chapter 1: TypeScript Basics Technical requirements Understanding the benefits of TypeScript Catching coding errors early Better developer experience and productivity Using future JavaScript features Understanding basic types Creating interfaces, types aliases, and classes Properties Method signatures Optional properties and parameters Readonly properties Extending interfaces Primitive types Type annotations Type inference Any Void Never Enumerations Objects Arrays Interfaces Type aliases Classes Basic classes Implementing interfaces Constructors Extending classes Abstract classes Access modifiers Property setters and getters Static Structuring code into modules Module formats Exporting Importing Default exports Configuring compilation 1 7 8 9 9 11 11 12 12 13 15 16 17 17 19 21 23 25 27 27 29 32 34 35 36 37 37 39 39 41 42 44 45 46 48 49 49 51 52 52
分享到:
收藏